1. 程式人生 > 程式設計 >mybatis使用foreach語句實現IN查詢(三種)

mybatis使用foreach語句實現IN查詢(三種)

foreach語句中, collection屬性的引數型別可以使:List、陣列、map集合

collection: 必須跟mapper.java中@Param標籤指定的元素名一樣

item : 表示在迭代過程中每一個元素的別名,可以隨便起名,但是必須跟元素中的#{}裡面的名稱一樣。

  • index :表示在迭代過程中每次迭代到的位置(下標)
  • open :字首, sql語句中集合都必須用小括號()括起來

close :字尾

  • separator :分隔符,表示迭代時每個元素之間以什麼分隔

Mybatis多條件查詢使用IN語句查詢foreach使用方式

#{}是預編譯處理,KaTeX parse error: Expected 'EOF',got '#' at position 20: …符串替換。mybatis在處理#̲{}時,會將sql中的#{}替…{}時,就是把${}替換成變數的值。使用#{}可以有效的防止SQL注入,提高系統安全性。

例如:

# 是將傳入的值當做字串的形式,eg:select id,name,age from student where id =#{id},當前端把id值1,傳入到後臺的時候,就相當於 select id,age from student where id =‘1'.

$ 是將傳入的資料直接顯示生成sql語句,eg:select id,age from student where id =${id},age from student where id = 1.

(1)$ 符號一般用來當作佔位符,常使用Linux指令碼的人應該對此有更深的體會吧。既然是佔位符,當然就是被用來替換的。知道了這點就能很容易區分$和#,從而不容易記錯了。

(2)預編譯的機制。預編譯是提前對SQL語句進行預編譯,而其後注入的引數將不會再進行SQL編譯。我們知道,SQL注入是發生在編譯的過程中,因為惡意注入了某些特殊字元,最後被編譯成了惡意的執行操作。而預編譯機制則可以很好的防止SQL注入。

select * from HealthCoupon where useType in ( '4','3' )

其中useType=“2,3”;這樣的寫法,看似很簡單,但是MyBatis不支援。。但是MyBatis中提供了foreach語句實現IN查詢

正確的寫法有以下幾種寫法:

(一)、selectByIdSet(List idList)

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 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>

到此這篇關於mybatis使用foreach語句實現IN查詢(三種)的文章就介紹到這了,更多相關mybatis foreach 查詢內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!