1. 程式人生 > 其它 >mybatis-plus 使用In查詢

mybatis-plus 使用In查詢

第一種
在Dao介面中自定義SQL查詢,拼接xml字串

UserDaoMapper.java

@Select("<script>"
+"select * from user where id in"
+ "<foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'>"
+ "#{id}"
+ "</foreach>"
+ "</script>")
List<User> getUserList(@Param("ids") List<String> ids);

第二種
在Mapper.xml中自定義SQL

UserDaoMapper.xml

<delete id="deleteUserByIds" parameterType="String">
delete from t_user where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>

UserDaoMapper.java

/**
* 批量刪除使用者
*
* @param ids 需要刪除的資料
* @return 結果
*/
public int deleteOperLogByIds(String[] ids);

備註:

標籤的collection引數的設定問題,如果引數像上面的例子這樣用@Param註解表明了,則用@Param標明的值,否則:

如果傳入的是單引數且引數型別是一個List的時候,collection屬性值為list
如果傳入的是單引數且引數型別是一個array陣列的時候,collection的屬性值為array
如果傳入的引數是多個的時候,我們就需要把它們封裝成一個Map了,當然單引數也可以,collection的屬性值為Map的key

第三種
List<User> list = this.baseMapper.selectList(new LambdaQueryWrapper<User>().in(User::getUserId,new String[]{"11","22","33","44"}));
List<User> list2 = this.baseMapper.selectList(new LambdaQueryWrapper<User>().in(User::getUserId,new ArrayList<String>(){{this.add("11");this.add("22")}}));

備註:

QueryWrapper + lambda = LambdaQueryWrapper