标签
<foreach collection="" item="" index="" open="" separator="" close=""></foreach>
collection为集合名 item 表示集合中每一个元素 进行迭代时的别名, index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置, open 表示该语句以什么开始, separator 表示在每次进行迭代之间以什么符号作为分隔 符, close 表示以什么结束。
示例:
dao层方法代码
List<Customer> selectByIds(@Param("ids") Integer[] ids);
mapper使用foreach标签
<select id="selectByIds" resultType="Customer"> select * from WXBHPT_V_Customers <where> <if test='ids!=null '> customid in <foreach collection="ids" item="id" open="(" separator="," close=")" index="index"> #{id} </foreach> </if> </where> order by customid; </select>
拼接结果为:
select * from WXBHPT_V_Customers where customid in (?,?,?)
ps:如果ids是某个bean对象的集合或数组, #{id.xxx} (xxx为属性名) 可直接取值
bind标签
<bind name="" value="" />
name为变量取一个名字,以便在后面使用它
value的值
用法举例
dao代码
Integer count(@Param("search") String search);
mapper代码
<select id="count" resultType="Integer">
<bind name="pattern" value="'%' + _parameter.search + '%'" />
select count(*) from WXBHPT_V_Customers where search like #{pattern} order by customid
</select>
拼接结果
select count(*) from WXBHPT_V_Customers where search like %searchstr% order by customid