亲宝软件园·资讯

展开

mybatis-plus自定义排序的实现

Archie_java 人气:0

需求:

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.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.StdOutImpl

3.创建分页需要的缓存

@Configuration
@MapperScan("scan.your.mapper.package")
public class  MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @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<User> {
}

在启动类上加了@MapperScan(“com.example.mapper”)

6.测试

  @Test
    void 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);
    }

7.结果

img

 到此这篇关于mybatis-plus自定义排序的实现的文章就介绍到这了,更多相关mybatis-plus 自定义排序内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

加载全部内容

相关教程
猜你喜欢
用户评论