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


  • 2017-02-10 15:19:51

    Git:代码冲突常见解决方法

    如果系统中有一些配置文件在服务器上做了配置修改,然后后续开发又新添加一些配置项的时候, 在发布这个配置文件的时候,会发生代码冲突:

  • 2017-02-10 15:24:14

    linux学习之——vim简明教程

    学习 vim 并且其会成为你最后一个使用的文本编辑器。没有比这个更好的文本编辑器了,非常地难学,但是却不可思议地好用。 我建议下面这四个步骤: 存活 感觉良好 觉得更好,更强,更快 使用VIM的超能力

  • 2017-02-10 16:22:13

    git历史记录查询

    查看提交历史:git log 查看提交历史并显示版本间的差异:git log -p 查看指定历史:git log xxx(sha1值) -p 查看提交历史(指定时间):

  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).