springboot项目使用Mybatis的分页插件

1. 引入依赖

在 pom.xml 文件中添加 MyBatis 和分页插件的依赖:

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

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>{pagehelper-spring-boot-starter-version}</version>
</dependency>

注意替换 {mybatis-spring-boot-starter-version} 和 {pagehelper-spring-boot-starter-version} 为对应的版本号。

2. 配置分页插件

在 Spring Boot 的配置文件 application.yml 中添加分页插件的配置参数:

pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

其中 helperDialect 表示数据库方言,这里以 MySQL 为例;reasonable 表示是否合理化查询,具体含义可以参考官方文档;supportMethodsArguments 表示支持通过方法参数来传递分页参数;params 表示使用 countSql 来统计总数,这样可以避免复杂 SQL 的性能问题。

3. 接口层代码

在接口层使用 com.github.pagehelper.PageHelper 类来设置分页参数,例如:

import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getUsers(int pageNum, int pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.getUsers();
    }
}

这里使用 startPage() 方法来设置分页参数,其中 pageNum 表示当前页码,pageSize 表示每页的记录数。

4. DAO 层代码

在 DAO 层的 SQL 中使用 MyBatis 分页插件提供的分页方式进行分页查询,例如:

<select id="getUsers" resultType="User">
    select * from user
</select>

注意不要在 SQL 中手动拼接分页参数,否则会导致性能问题。

猜你喜欢

转载自blog.csdn.net/weixin_59367964/article/details/130539084
今日推荐