mybatisplus的查询所有_凌雪-Mybatis 分页查询简单实现方式(Mybatis Plus)

一般物理分页,即通过sql语句分页,都是在sql语句后面添加limit分页语句,在xml文件里传入分页的参数,再多配置一条sql,用于查询总数:

select * from student limit #{currIndex} , #{pageSize}

select count(*) from student

这样可以实现分页,但是每条sql都这样写,很冗余,而且不好维护,所以高级一点的方式就是自定义的一个拦截器,拦截所有需要分页的查询语句,并且利用获取到的分页相关参数统一在sql语句后面加上limit分页的相关语句,一劳永逸,不需要再每条语句都配置一下,拦截器具体怎么实现不说了,因为Mybatis Plus 已经有类似这样一个拦截器的分页插件,利用这个分页插件,不需要自己写拦截器就可以轻松实现分页查询:

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

1、 添加Mybatis-plus

com.baomidou

mybatis-plus

2.1.8

2、配置拦截器

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

/**

* mybatis-plus配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus提供了非常方便的分页查询功能,可以直接使用Page类来进行分页查询。 使用MyBatis-Plus的分页查询,需要进行以下步骤: 1. 引入MyBatis-Plus的依赖:在pom.xml中添加以下依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> ``` 2. 定义实体类:定义需要进行分页查询的实体类,并使用注解@TableField进行字段映射。 3. 定义Mapper接口:定义Mapper接口,并继承BaseMapper类,继承BaseMapper类后,MyBatis-Plus会自动提供一些基本的CRUD操作。 ``` public interface UserMapper extends BaseMapper<User> {} ``` 4. 分页查询:在Service层中调用分页查询方法,使用Page对象设置分页参数,然后调用selectPage方法进行分页查询。 ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public Page<User> getUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectPage(page, null); } } ``` 如果需要自定义sql分页,可以在xml中使用MyBatis的分页插件进行分页查询。 1. 引入分页插件:在pom.xml中添加以下依赖: ``` <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency> ``` 2. 配置分页插件:在MyBatis的配置文件中配置分页插件。 ``` <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="dialect" value="mysql"/> </plugin> </plugins> ``` 3. 自定义sql分页查询:在xml中使用分页插件的PageHelper.startPage方法进行分页查询。 ``` <select id="getUserList" resultMap="userMap"> select * from user <where> <if test="name != null"> and name like concat('%',#{name},'%') </if> </where> order by id desc </select> ``` ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public PageInfo<User> getUserList(int pageNum, int pageSize, String name) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.getUserList(name); return new PageInfo<>(userList); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值