mybatis-plus中的in查询的详细使用方法解析

月亮捕捞者 2021-08-10 11:35:44 浏览数 (16634)
反馈

如果是List类型的String,例如:List<String>这种类型的,就直接放值就可以了,本文讲的是当你查询到的是一个list集合如何遍历取值,否则要写sql和接口就显得很麻烦。

步骤如下:

//查询到list集合
List<User> userList = userService.selectById(id);
//结果集
List<String> resultList = new ArrayList<>();
//遍历集合取值
 userList .forEach(item->{
      resultList.add(item.getYouNeedId());
 });
 //条件构造器in上手使用
 QueryWrapper<User> qw = new QueryWrapper<>();
 qw.in("you_need_id", resultList);
 //这里有个分页的查询,你也可以不用分页,用mybatisplus里面封装的其他方法
 IPage<User> userIPage = userMapper.selectPage(page, qw);
 //返回查询结果,getRecords也是mybatisplus里面封装的方法
 return contractRecordIPage.getRecords();

 补充:Mybatis Plus 通过QueryWrapper做查询时in()方法的使用

UserId类:

@Data
public class UserId {
 /**
  * 用户id集合
  */
 private JSONArray userIdList;
}

测试类:

public class Test{
 public JSONArray getUserStatusList(UserId userId) {
  // 添加非空校验,JsonArray对象为null或长度为0时直接返回,不执行sql
  if (userId.getUserIdList() == null  || userId.getUserIdList().size() == 0) {
  return new JSONArray();
  }
  // 创建查询Wrapper对象
  QueryWrapper wrapper = new QueryWrapper();
  wrapper.in("user_id", userId.getUserIdList());
  List list = baseMapper.selectObjs(wrapper);
  return JSONArray.parseArray(JSON.toJSONString(list));
 }
}

注意:如果不加非空校验,当集合为空集合时会报SQL的异常

到此本篇关于mybatis-plus中in查询的使用和步骤就介绍到这了,想要了解更多相关mybatis plus in内容,可以搜索W3Cschool以前的文章或继续浏览下面的相关文章!

0 人点赞