mybatis foreach标签

情景:查询数据库中文章的相关文章   文章为一个表 字段tags为相关文章字符串中间用','逗号进行啦分割数据库

查询完一个文章后能够把tags字段构造为一个List<String> 而后利用这个集合做为条件来查询app

<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>
字符串

看。 foreach 生成的效果是集合 转化为下面的it

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


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

item表示集合中每个元素进行迭代时的别名.List

index指 定一个名字,用于表示在迭代过程当中,每次迭代到的位置.select

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

生成的SQL为

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

foreach : 用的更多的地方为: 根据Id批量删除    /    判断什么 in 集合中(此时须要生成(**,***,)的形式)