在mapper.xml中,使用List类型的参数来组织动态SQL,很多时候不知道foreach标签的collection属性到底应该是collection=“list” 还是collection=“list的参数名”。代码如下:
//伪代码
public interface UserMapper{
/**
*这个方法的参数没有使用@Param注解,在foreach标签中,collection=“list”
*/
int updateUserLists(List<String> userLists);
/**这个参数使用了@Param注解,在foreach标签中,collection=“userLists”
*如果不加@Param注解指定参数名,而直接这样用,xml文件会报错
*/
int modifyByUserLists(@Param("userLists") List<String> userLists)
}
//伪代码 Mapper.xml
<update id="updateUserLists" resultType="String" >
UPDATE table_user SET user_name = "姓名"
WHERE user_id IN
<foreach collection="list" item="userId" open="(" close=")" separator="," >
#{userId}
</foreach>
</update>
<update id="modifyByUserLists" resultType="String" >
UPDATE table_user SET user_salary = "799878978"
WHERE user_id IN
<foreach collection="userLists" item="item" open="(" close=")" separator="," >
#{item}
</foreach>
</update>
参数是list类型时,collection=“list” ,参数是数组类型collection=“array”;