0
点赞
收藏
分享

微信扫一扫

spring boot使用mybatis进行分页实战


文章目录

  • 环境介绍
  • 添加依赖
  • application.properties配置
  • 控制器演示代码
  • 浏览器访问结果

前几天研究了Spring Boot中访问关系型数据库的三个框架,其中mybatis使用最多,所以继续集成了一下分页插件,不仅集成简单使用也简单。

环境介绍

Spring Boot版本:2.7.0
JDK版本:1.8

添加依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- 注意pagehelper-spring-boot-starter使用1.4.2版本,
         因为此版本解决了Spring Boot高版本带来的循环依赖问题。-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.4.2</version>
    </dependency>

application.properties配置

pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

控制器演示代码

@RestController
public class MybatisController {

    protected final static Logger logger = LoggerFactory.getLogger(MybatisController.class);

    @Autowired
    public TeacherMapper teacherMapper;

    @GetMapping("mybatis/teachers")
    public List<Teacher> teachers(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        return teacherMapper.selectList();
    }
}

浏览器访问结果

http://127.0.0.1:8080/mybatis/teachers?pageNo=1&pageSize=5

[{"id":1,"name":"李继","age":35},{"id":2,"name":"李继","age":35},{"id":3,"name":"李继","age":35},{"id":4,"name":"王三","age":22},{"id":5,"name":"王三5","age":22}]

分页插件:pagehelper-spring-boot-starter 工程其它配置:参考《Spring Boot访问关系型数据库三剑客JDBC、JPA、Mybatis》


举报

相关推荐

0 条评论