当我们需要遍历一个集合类的对象时,通常需要使用foreach标签,下面,我们先以遍历List为例,写两种情况下如何遍历。
1.遍历List
1.1.只传入了一个List参数
当我们的Mapper类中只需要传入一个List参数,如下例:
public int updateByIdList(List<Long> myIdList);
在对应的xml文件中,我们只需要标明 list 即可:
<update id="updateByIdList">
UPDATE lalala_table
SET status= 1
<where>
id IN
<foreach collection="list" item="item_id" open="(" separator="," close=")">
${item_id}
</foreach>
</where>
</update>
1.2.List只是多个参数中的一个参数
当我们需要既传递List,又需要传递其它的参数,我们应该首先封装一个数据类,这样也方便我们对于每一个参数进行注释,我个人不推荐使用HashMap直接传入。例如,我们有下面这样一个参数类:
@Setter
@Getter
public class MyDTO{
private List<Long> myIdList;
private Integer age;
private String name;
}
对应mapper文件中,我们直接传入这个对象,对于xml文件中,我们对应好parameterType与resultType。在使用list的时候,直接写变量的名称即可:
<select id="getSomething" parameterType="com.xxx.MyDTO"
resultType="com.xxx.Student">
SELECT
*
FROM
x
<where>
<if test="null!=myIdList and myIdList.size()>0">
AND x.`id` IN
<foreach collection="myIdList" item="item" open="(" separator="," close=")">
${item}
</foreach>
</if>
<if test="null!= age">
AND x.`age`= #{age,jdbcType = INTEGER }
</if>
<if test="null!= name">
AND x.`name`= #{name, jdbcType = VARCHAR}
</if>
</where>
</select>
TO BE CONTINUED...