mybatis foreach标签详解,逗号,and还有or,留一个

2019-10-30 13:25:17

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

查询完一个文章后可以把tags字段构造为一个List<String> 然后利用这个集合作为条件来查询


 

1
2
3
4
5
6
7
<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表示以什么结束.

 

1
2
3
4
5
6
7
<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> 来查。

 

但是查不到数据
需要使用如下方式:

1
2
3
4
5
6
7
<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 集合中(此时需要生成(**,***,)的形式)


  • 2018-10-10 14:29:01

    php header()函数设置页面Cache缓存

    ​ header()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它之前不能任何输出,包括空格。

  • 2018-10-11 23:58:07

    Linux实例带宽和CPU跑满或跑高排查

    使用云服务器 ECS 时,若出现服务的速度变慢,或 ECS 实例突然断开,可以考虑服务器带宽和 CPU 是否有跑满或跑高的问题。若您预先创建报警任务,当带宽和 CPU 跑满或跑高时,系统将自动进行报警提醒。Linux 系统下,您可以按如下步骤进行排查:

  • 2018-10-15 09:22:07

    使用epublib解析epub文件(章节内容、书籍菜单)

    前阵子在android上解析epub格式的书籍。发现了这个开源的epub解析库。相关资料甚少!折腾了一阵子,发现其实光使用的话还是挺简单的。真是萌萌哒~下面简单介绍一下epublib。