springboot项目使用Mybatis的分页插件

文章介绍了如何在SpringBoot项目中集成MyBatis和PageHelper分页插件,包括在pom.xml添加依赖,配置application.yml以设置分页参数,以及在接口层和DAO层如何使用分页功能。合理配置能避免手动拼接SQL,提高查询性能。
摘要由CSDN通过智能技术生成

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 中手动拼接分页参数,否则会导致性能问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桑稚远方~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值