App下載

mybatis-plus中的in查詢的詳細(xì)使用方法解析

月亮捕撈者 2021-08-10 11:35:44 瀏覽數(shù) (18121)
反饋

如果是List類型的String,例如:List<String>這種類型的,就直接放值就可以了,本文講的是當(dāng)你查詢到的是一個(gè)list集合如何遍歷取值,否則要寫sql和接口就顯得很麻煩。

步驟如下:

//查詢到list集合
List<User> userList = userService.selectById(id);
//結(jié)果集
List<String> resultList = new ArrayList<>();
//遍歷集合取值
 userList .forEach(item->{
      resultList.add(item.getYouNeedId());
 });
 //條件構(gòu)造器in上手使用
 QueryWrapper<User> qw = new QueryWrapper<>();
 qw.in("you_need_id", resultList);
 //這里有個(gè)分頁的查詢,你也可以不用分頁,用mybatisplus里面封裝的其他方法
 IPage<User> userIPage = userMapper.selectPage(page, qw);
 //返回查詢結(jié)果,getRecords也是mybatisplus里面封裝的方法
 return contractRecordIPage.getRecords();

 補(bǔ)充:Mybatis Plus 通過QueryWrapper做查詢時(shí)in()方法的使用

UserId類:

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

測(cè)試類:

public class Test{
 public JSONArray getUserStatusList(UserId userId) {
  // 添加非空校驗(yàn),JsonArray對(duì)象為null或長度為0時(shí)直接返回,不執(zhí)行sql
  if (userId.getUserIdList() == null  || userId.getUserIdList().size() == 0) {
  return new JSONArray();
  }
  // 創(chuàng)建查詢Wrapper對(duì)象
  QueryWrapper wrapper = new QueryWrapper();
  wrapper.in("user_id", userId.getUserIdList());
  List list = baseMapper.selectObjs(wrapper);
  return JSONArray.parseArray(JSON.toJSONString(list));
 }
}

注意:如果不加非空校驗(yàn),當(dāng)集合為空集合時(shí)會(huì)報(bào)SQL的異常

到此本篇關(guān)于mybatis-plus中in查詢的使用和步驟就介紹到這了,想要了解更多相關(guān)mybatis plus in內(nèi)容,可以搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章!

0 人點(diǎn)贊