#使用mybatis-plus来自定义排序
需求:
- 先时间升序排序,相同的时间在按状态排序,
- 状态的顺序为1 在线 4 潜伏 2 隐身 3 离开,
- 状态相同在按姓名升序排序
- 对排序好的数据进行分页
- 运用mybatis-plus中QueryWrapper
2.配置文件org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-starter-testtest com.baomidou mybatis-plus-boot-starter3.5.1 org.projectlombok lomboktrue mysql mysql-connector-javaruntime
spring: # 配置数据源信息 datasource: # 配置数据源类型 type: com.zaxxer.hikari.HikariDataSource # 配置连接数据库信息 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false username: root password: 123456 mybatis-plus: configuration: # 配置MyBatis日志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl3.创建分页需要的缓存
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
4.创建实体类
@Data
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
private Integer state;//1 在线 4 潜伏 2 隐身 3 离开
private Date time;
}
5.mapper
public interface UserMapper extends BaseMapper{ }
在启动类上加了@MapperScan("com.example.mapper")
6.测试 @Test
void selectUser(){
QueryWrapper wrapper=new QueryWrapper<>();
//时间升序排序
wrapper.lambda().orderByAsc(User::getTime);
//状态的自定义排序,和姓名排序
wrapper.orderByAsc(" field(state,1,4,2,3)");
wrapper.lambda().orderByAsc(User::getName);
//分页
Page page=new Page<>();
page.setSize(3);//每页的长度
page.setPages(1);//第几页
userMapper.selectPage(page,wrapper);
}
7.结果



