需求:
- 先时间升序排序,相同的时间在按状态排序,
- 状态的顺序为1 在线 4 潜伏 2 隐身 3 离开,
- 状态相同在按姓名升序排序
- 对排序好的数据进行分页
- 运用mybatis-plus中QueryWrapper
1.导入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency></dependencies>
2.配置文件
spring:# 配置数据源信息datasource:# 配置数据源类型type: com.zaxxer.hikari.HikariDataSource# 配置连接数据库信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falseusername: rootpassword: 123456mybatis-plus:configuration: # 配置MyBatis日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.创建分页需要的缓存
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {/*** 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)*/@Beanpublic 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<User> {
}
在启动类上加了@MapperScan(“com.example.mapper”)
6.测试
@Testvoid selectUser(){QueryWrapper<User> 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);}