当表字段需要根据id进行更新的时候,如果有多条数据需要根据对应的id更新,那么就可以考虑动态更新。
假设需要更新表中的state状态字段,以及需要根据对应的id更新表中的number字段。直接上代码
java代码部分:写java代码部分是为了更好的理解参数在sql语句中是怎样被封装进去的。
@Responsebody
@RequestMapping("/XXX.do")
public void XXX(ModelMap model ,HttpServletRequest request,HttpServletResponse response) {
// 这里是要传到mapper中的集合,集合里面封装的是你要查询的数据的idList<String> idList = new ArrayList<String>
idList.add("id1");
idList.add("id2");
// 创建一个集合,里面封装你要更新的字段的对象
List<Shelf> shelfList = new ArrayList<Shelf>();
shelf.setId(id1);
shelf.setNumber(number);
shelfList.add(shelf);
// 创建map的过程就省略了,把封装了id的集合放到你的map集合中
map.put("idList",idList);
map.put("state","1");
// 把map作为参数传到对应的Mapper中
}
sql语句的写法:
<update id = "updateStateAndNumber" parameterType = "hashmap" >
update table(table写自己的表名称)
set
state = # {state,jdbcType=INTEGER}, (第一个state是要更新的表字段名称,第二个state是map中的key值)
number = case
id
<foreach collection="shelfList" item="item" index ="index" >
when #{item.id} then #{item.number}
end
where
id in
<foreach collection="idList" item="item" index ="index" open="(" separator="," close=")">
#{item}
</foreach> </update>
number根据对应的id进行更新。