掉进去过的坑,爬出来以后一定要总结一下!
情景1:
update stu_pos set read_or_not = 1 where stu_pos_id in (?,?,?,?);
此时需要传递单参数:
mapper:
<update id="updateReadFalseToTrue">
update stu_pos set read_or_not = 1 where stu_pos_id in
<foreach collection="list" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>
</update>
Dao:
public void updateReadFalseToTrue(List<Integer> ids);
结果:成功。
单参数:mapper中#{}的名称不一定需要和dao中传入的参数名一致。因为只有唯一的一个,系统完全可以识别到。
情景2:
update stu_pos set read_or_not = ? where stu_pos_id in (?,?,?,?);
此时需要传递多参数:int & list
mapper:
<update id="updateReadFalseToTrue">
update stu_pos set read_or_not = #{read_or_not} where stu_pos_id in
<foreach collection="list" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>
</update>
Dao:
因为mybatis不支持传入多参数,所以在传入多参时需要在dao层用@Para(“参数名”)注解,且参数名需要和mapper中#{}一一对应才可识别的到。
public void updateReadFalseToTrue(@Param("read_or_not") int read_or_not, @Param("ids") List<Integer> ids);
结果:报错500,且提示参数list不存在。
疑惑:list是啥 我传的集合叫ids又不是list!
后知后觉:oh 我把mapper中的collection理解错了!!! collection才是传入集合的名称!!!而item就是每次迭代的项目。。。
按照集合中的意义重新命名和对照以后,修改如下:
<update id="updateReadFalseToTrue">
update stu_pos set read_or_not = #{read_or_not} where stu_pos_id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
结果:成功!!