阅读文本大概需要3分钟。
在做mybatis的mapper.xml文件的时候,时常遇到一些需要批量操作的情况,这个时候mybatis的foreach标签就派上用场了。
foreach元素的属性主要有item,index,collection,open,separator,close。
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有以下3种情况:
0x01:传入的参数为List
对应的Dao中的Mapper文件是:
public List<User> selectByIds(List<Integer> userIds);
xml文件代码片段:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
0x02: 传入的参数为Array
对应的Dao中的Mapper文件是:
public List<User> selectByIds(int[] userIds);
xml文件代码片段:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
0x03: 传入的参数为Map
对应的Dao中的Mapper文件是:
public List<User> selectByIds(Map<String, Object> params);
xml文件代码片段:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="userIds" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
Map的时候需要注意的是:collection的值ids是存储在map中的key,比如:
map.put("userIds",userIds));