1.spring集成mybatis分页
一、首先我们需要引入 pagehelper 插件
com.github.pagehelper
pagehelper
5.1.10
二、然后,我们需要在sqlsessionFactory中配置插件
三、然后就可以使用了,这里我写了一个测试。
@Autowired
private PurchaseMapper purchaseMapper;
@Test
public void dd(){
//查询第几页,查询一条数据
Page page = new Page<>(1,3);
//根据条件查询数据
IPage iPage = purchaseMapper.selectPage(page, null);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总页数:" + iPage.getPages());
System.out.println("当前页:" + iPage.getCurrent());
System.out.println("数据总条数:" + iPage.getSize());
System.out.println("获取数据:" + iPage.getRecords());
}
2.springboot集成mybatisPlus分页
一、使用mybatisplus我么你需要导入mybatisplus依赖
com.baomidou
mybatis-plus-boot-starter
3.4.3
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
druid
1.2.8
二、创建MybatisPlus分页的拦截器,否则分页就会没有效果
package com.example;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.mapper")
public class MyConfig {
@Bean
public MybatisPlusInterceptor MybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//分页
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
//乐观锁
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
三、mapper接口中继承BaseMapper< >
package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper {
}
四、application.yml中配置mybatisplus的基本配置,否则会报一些错
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&useAffectedRows=true
username: root
password: 199000222
mybatis-plus:
global-config:
db-config:
id-type: auto
configuration:
map-underscore-to-camel-case: false #关闭mytabisplus的驼峰命名
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启mybatisplus日志
五、测试
@Autowired
private UserMapper userMapper;
@Test
public void testSelectPage() {
QueryWrapper wrapper = new QueryWrapper();
//设置查询条件
wrapper.gt("id", 1); //年龄大于20岁
Page page = new Page<>(1, 3); //查询第一页,查询一条数据
//根据条件查询数据
IPage iPage = userMapper.selectPage(page, wrapper);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总页数:" + iPage.getPages());
System.out.println("当前页:" + iPage.getCurrent());
System.out.println("数据总条数:" + iPage.getSize());
List users = iPage.getRecords();
for (User user : users) {
System.out.println("user = " + user);
}
}
六、结果。我们可以看到日志中的SQL语句已经自己进行了limit分页,查询的数据也为三条。