一直用的的mybatis进行查询数据,对于有些内容容易忘记,这里整理一下,如果有纰漏请指正!
先上简单的代码
<select id="getUsernameList" parameterType="java.util.List" resultType="java.lang.String">
select
username
from
sys_user su
where
su.user_id in
<foreach collection="userIdList" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
上面的代码出现了错误,collection=""的值要根据不同的情况来区分:
对于collection中的参数写什么有不同的情况。
//dao层接口伪代码
public interface UserMapper{
//这个方法的参数没有使用@Param注解,在foreach标签中,collection=“list”
int updateByUserIds(List<Integer> userIds);
//这个参数使用了@Param注解,在foreach标签中,collection=“userIds”
//如果不加@Param注解指定参数名,而直接这样用,xml文件会报错
int modifyByUserIds(@Param("userIds") List<Integer> userIds)
}
//UserMapper.xml 伪代码
<update id="updateByUserIds" resultType="int" >
UPDATE table_user SET user_name = "用户名"
WHERE user_id IN
<foreach collection="list" item="userId" open="(" close=")" separator="," >
#{userId}
</foreach>
</update>
<update id="modifyByUserIds" resultType="int" >
UPDATE table_user SET user_salary = "原来的2倍"
WHERE user_id IN
<foreach collection="userIds" item="userId" open="(" close=")" separator="," >
#{userId}
</foreach>
</update>
使用@Param注解时,MyBatis将你注解指定的参数名作为Key, 将你的参数作为Value,封装成了一个map,传递到了UserMapper.xml中。
另外,参数是list类型时,collection=“list” ,参数是数组类型collection=“array”。
参考网址:
https://blog.csdn.net/HairyCoder/article/details/106539616