Mybatis-Plus分页查询
Posted 为BUG消得人憔悴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Plus分页查询相关的知识,希望对你有一定的参考价值。
Mybatis-Plus分页查询
1、导入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2、编写配置文件.YML
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis
driver-class-name: com.mysql.jdbc.Driver
#配置日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3、编写持久类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class user implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@Version//乐观锁注解
private Integer version;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
4、编写mapper类
@Repository
public interface mapper extends BaseMapper <user> {
}
5、编写config配置类
//扫描mapper包
@MapperScan("com.xys.Mapper")
@EnableTransactionManagement
@Configuration//配置类
public class MybatisConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
6、编写handle类
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert info....");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update info....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
7、分页查询
分页在网站使用的十分之多!
1、原始的limit进行分页
2、pageHelper第三方插件
3、MP其实也内置了分页插件!
//测试分页查询
@Test
void testPage(){
Page<user> page=new Page<>(1,5);
mapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
以上是关于Mybatis-Plus分页查询的主要内容,如果未能解决你的问题,请参考以下文章
Mybatis-plus系列使用Mybatis-plus的selectPage()分页查询没生效
Mybatis-plus系列使用Mybatis-plus的selectPage()分页查询没生效