【日常笔记】mybatis 处理 in 语句的使用

在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。

foreach的参数:
foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
close表示以什么结束。

1. Mybatis生成select * from table where id in(1,2,...,n)语句的查询

我们一般的做法是在方法的参数处指定传入的参数名称,在xml中使用的时候,集合的名称要和方法的Param的名称一致,这样便于阅读和理解,然后是在对应的xml文件中使用foreach循环。

java 代码:

public abstract List<Model> findByIds(@Param("ids")List<Integer> ids);

对应的xml代码如下:

select * from table
<where>
    id in <foreach collection="ids" item="item" index="index" 
open="(" separator="," close=")">#{item}</foreach>
</where>

判断集合是否有值

<if test="ids!=null and ids.size()>0"></if>
原文地址:https://www.cnblogs.com/miskis/p/5520136.html