當我們要查詢一些人的信息時,但這些人的id是由用戶確定的,就會采用list集合或者數組作為參數傳入方法中,
public List findSomeUsers(List noList);
而在xml文件中就可以用Forreach動態SQL解決
<select id="findSomeUsers" resultType="user3" parameterType="list">
select * from user where id in
<foreach collection="noList" index="index" item="no" open="(" separator="," close=")">
#{no}
</foreach>
</select>
1
2
3
4
5
6
測試代碼:
List<Integer> noList = new ArrayList<>();
noList.add(1);
noList.add(2);
noList.add(3);
noList.add(6);
List<User> list = mapper.findSomeUsers(noList);
1
2
3
4
5
6
結果卻出錯了,原因是找不到noList這個參數,為什么呢?
接着我在接口方法中的參數前面用注解的方式加上了@Param(“noList”),接着測試了一下,
結果並沒有報錯,且查出了結果
sql語句是select * from user where id in ( ? , ? , ? , ? )
User [id=1, name=張三, age=23]
User [id=2, name=李四, age=30]
User [id=3, name=張無忌, age=30]
User [id=6, name=張良, age=30]
1
2
3
4
然后上網查了一下,還有一種說法是:
因為 傳遞一個 List 實例或者數組作為參數對象傳給 MyBatis,MyBatis 會自動將它包裝在一個 Map 中,用名稱在作為鍵。List 實例將會以“list” 作為鍵,而數組實例將會以“array”作為鍵
接着我恢復了之前發生錯誤的環境,把xml中的foreach中的collection改成了list,其他的都沒改,沒有報錯,也可以查詢出結果。
因此,解決這個異常的兩種方式是:
1.在方法參數前面加上你遍歷的集合的名稱,比如你在foreach的collection中寫的是noList,那么你就在傳入的list參數前面加上一個注解@Param(“noList”)。
2.將foreach的collection中的值改成list即可。
————————————————
版權聲明:本文為CSDN博主「鑫爵」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_37745636/article/details/99091931