Java-MyBatis-雜項: MyBatis 中 in 的用法2
ylbtech-Java-MyBatis-雜項: MyBatis 中 in 的用法2 |
1.返回頂部 |
一、簡介
在SQL語法中如果我們想使用in的話直接可以像如下一樣使用:
select * from HealthCoupon where useType in ( ‘4‘ , ‘3‘ )
但是如果在MyBatis中的使用in的話,像如下去做的話,肯定會報錯:
Map<String, Object> selectByUserId(@Param("useType") String useType) <select id="selectByUserId"resultMap="BaseResultMap" parameterType="java.lang.String"> select * from HealthCoupon where useType in (#{useType,jdbcType=VARCHAR}) </select>
其中useType="2,3";這樣的寫法,看似很簡單,但是MyBatis不支持。。但是MyBatis中提供了foreach語句實現IN查詢,foreach語法如下:
foreach語句中, collection屬性的參數類型可以使:List、數組、map集合
?collection: 必須跟mapper.java中@Param標簽指定的元素名一樣
?item: 表示在叠代過程中每一個元素的別名,可以隨便起名,但是必須跟元素中的#{}裏面的名稱一樣。
index:表示在叠代過程中每次叠代到的位置(下標)
open:前綴, sql語句中集合都必須用小括號()括起來
?close:後綴
separator:分隔符,表示叠代時每個元素之間以什麽分隔
正確的寫法有以下幾種寫法:
(一)、selectByIdSet(List idList)
如果參數的類型是List, 則在使用時,collection屬性要必須指定為 list
List<User> selectByIdSet(List idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE id IN <foreach collection="list" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
(二)、List<User> selectByIdSet(String[] idList)
如果參數的類型是Array,則在使用時,collection屬性要必須指定為 array
List<User> selectByIdSet(String[] idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE id IN <foreach collection="array" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
(三)、參數有多個時
當查詢的參數有多個時,有兩種方式可以實現,一種是使用@Param("xxx")進行參數綁定,另一種可以通過Map來傳參數。
3.1 @Param("xxx")方式
List<User> selectByIdSet(@Param("name")String name, @Param("ids")String[] idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE name=#{name,jdbcType=VARCHAR} and id IN <foreach collection="idList" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
3.2 Map方式
Map<String, Object> params = new HashMap<String, Object>(2); params.put("name", name); params.put("idList", ids); mapper.selectByIdSet(params); <select id="selectByIdSet" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_user where name = #{name} and ID in <foreach item="item" index="index" collection="idList" open="(" separator="," close=")"> #{item} </foreach> </select>2、
2.返回頂部 |
3.返回頂部 |
4.返回頂部 |
5.返回頂部 |
6.返回頂部 |
作者:ylbtech 出處:http://ylbtech.cnblogs.com/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。 |
Java-MyBatis-雜項: MyBatis 中 in 的用法2