mybatis foreach標簽的解釋 與常用之處


情景:查詢數據庫中文章的相關文章   文章為一個表 字段tags為相關文章字符串中間用','逗號進行啦分割

查詢完一個文章后可以把tags字段構造為一個List<String> 然后利用這個集合作為條件來查詢

 

<select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper">
  select * from t_news n where 
  <foreach collection="listTag" index="index" item="tag" open="("
    separator="," close=")">
   #{tag} in n.tags
  </foreach>
 </select>

  

看。 foreach 生成的效果是集合 轉化為下面的

 select * from t_news n where ( ? in n.tags , ? in n.tags )

 


foreach元素的屬性主要有 item,index,collection,open,separator,close。

item表示集合中每一個元素進行迭代時的別名.

index指 定一個名字,用於表示在迭代過程中,每次迭代到的位置.

open表示該語句以什么開始,separator表示在每次進行迭代之間以什么符號作為分隔 符.

close表示以什么結束.

 

<select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper">
  select * from t_news n where 
  <foreach collection="listTag" index="index" item="tag" open=""
    separator="or" close="">
   #{tag} in n.tags
  </foreach>
 </select>

  

所以 去除左右括號 和 把,改成 or 進行 。 就可以轉化為這種形式。
select * from t_news n where ? in n.tags or ? in n.tags   這樣可以用List<String> 來查。

 

但是查不到數據
需要使用如下方式:

<select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper">
  select * from t_news n where 
  <foreach collection="listTag" index="index" item="tag" open=""
    separator="or" close="">
    n.tags like  '%'||#{tag}||'%'
  </foreach>
<select>

  

生成的SQL為

select * from t_news n where n.tags like ? or n.tags like ?    

 

foreach : 用的更多的地方為: 根據Id批量刪除    /    判斷什么 in 集合中(此時需要生成(**,***,)的形式)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM