‹ 返回笔记 Esc·

MyBatis-Plus 问题与修复

MyBatis-Plus 中 Service 层随机查询写法 实现类似于SELECT * FROM ai_info ORDER BY RAND() LIMIT 10的随机查询操作: --- MP 执行…

MyBatis-Plus 中 Service 层随机查询写法

实现类似于SELECT * FROM ai_info ORDER BY RAND() LIMIT 10的随机查询操作:

1List<AiPromptInfo> infos = aiInfoService.getBaseMapper().selectList( new QueryWrapper<AiPromptInfo>().orderByAsc("RAND()") .last("LIMIT " + number));

MP 执行时输出SQL语句

1# application.yml文件中配置
2mybatis-plus:
3  configuration:
4    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

MP 查询条件为空字符串或 null 不加入此查询条件中

mybatis-plus 的条件构造器方法 eq()like()last()等这些方法能支持第三个参数 condition public Children eq(boolean condition, R column, Object val) {} condition是一个布尔值,当conditionfalse时,当前这个条件方法不会生效,即生成的 sql 不会拼接这个条件;所以在这个参数里判断查询参数是否为空即可。

1List<User> list = userService.lambdaQuery()
2.eq(phone != null && !"".equals(phone), User::getName, name).list();

MP mapper 层 lambda 查询

为了避免我们在代码中写类似的于user_name的硬编码 Lambda 的好处是降低代码的耦合性,不需要把字段名写死。

1List<User > users = userMapper.selectList(new QueryWrapper<User>().eq("user_name", id));
2// 替换成下面的
3List<User> user=userMapper.selectList(new QueryWrapper<User>().lambda().eq(User::getuserName, userName));

MP 分页条件查询

1Page<User> pageInfo = userService.lambdaQuery()
2.eq(name != null && !"".equals(name), User::getName, name)
3.eq(phone != null && !"".equals(phone), User::getPhone, phone)
4.page(new Page<>(pageNum, pageSize));

MP 查询指定字段

1Page<User> pageInfo = userService.lambdaQuery()
2.select(User::getId, User::getName, User::getPhone)
3.eq(name != null && !"".equals(name), User::getName, name)
4.eq(phone != null && !"".equals(phone), User::getPhone, phone)
5.page(new Page<>(pageNum, pageSize));
6// 查询出的实体类中的其他字段为null

MP or() 用法

1UserService.lambdaQuery()
2    .eq(User::getUnionid, unionid).eq(User::getWxAppid, 1)
3    .or()
4    .eq(User::getUnionid, unionid).eq(User::getWxAppid, 2)
5    .list();

MP 去重查询

1List<DetectHistory> lineNameList = detectHistoryService.query().select("distinct line_name").list();

MP lambdaQuery 查询实体过滤成指定字段

1List<String> companyNameList = companyService.lambdaQuery().select(Company::getName).list().stream().map(Company::getName).collect(Collectors.toList());

MP 解决分页不生效

1@Bean
2public MybatisPlusInterceptor mybatisPlusInterceptor() {
3    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
4    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
5    return interceptor;
6}

实体类 boolean 类型字段数据库转换问题

实体类is_delete类型为boolean, 对应数据库中的int类型时, 如果实体类不传参, 数据库中的is_delete字段接收不到值就默认为 0, 就算数据库中设置is_delete字段默认值为 1, 不传参也是为 0,故boolean类型必须得传值。


MP 只查表字段中的一列

1List<Integer> companyDeviceIds = companyDeviceService.lambdaQuery()
2    .eq(CompanyDevice::getCompanyId, companyId).list()
3    .stream().map(CompanyDevice::getDeviceId)
4    .collect(Collectors.toList());

MP >3.5.9 依赖无分页 PaginationInnerInterceptor

需要加 mybatis-plus-jsqlparser依赖,或者用小于或等于 3.5.8 的版本。