有时在开发中难免会遇到传入的参数为map类型的时候, map的key为数据库中的主键或者其他的唯一字段, value为需要进行插入的值,在mybaits的XML文件中进行遍历取出map参数中的值, 有两种方式进行处理
方法一:
xml文件中写法
<update id="updateInventoryBatch" parameterType="java.util.Map"> <foreach item="value" index="key" collection="inventoryMap" separator=";" > UPDATE yanxuan_inventory_transfer SET inventory = #{value}, is_inventory='1', create_time=sysdate() where sku_id=#{key} </foreach> </update>以上 collection ="inventoryMap" 表示的是dao中对应的map的@param的参数名称, index="key" 中的key表示的是map的key值, item="value" 表示的map的key所对应的value值 , 故直接#{key} 和#{value}进行取值即可
dao中的写法
longupdateInventoryBatch(@Param("inventoryMap") HashMap<String, Integer> inventoryMap);
第二中方式:
先遍历map的key, 得到所有的key值, 然后根据key获取对应的value值
xml文件中写法
<update id="updateInventoryBatch" parameterType="java.util.Map"> <foreach item="key" collection="inventoryMap.keys" separator=";" > UPDATE yanxuan_inventory_transfer SET inventory = #{inventoryMap[${key}]}, is_inventory='1', create_time=sysdate() where sku_id=#{key} </foreach> </update>以上c ollection="inventoryMap.keys" 表示的遍历map的key, 同理collection="inventoryMap.values"表示的是遍历的map 的value, item="key" 表示的是map的key, #{inventoryMap[${key}]}取出的是inventoryMap key所对应的value,
注意: ${key} 必须为使用${}取值, 不能使用#{}, 因为#{} 会自动加上"" 这样是获取不到value值的.
以上是演示mybatis进行批量更新的sql 如果想要实现的话 需要在jdbc_url 链接后面加上&allowMultiQueries=true
允许执行多个SQL语句才能正常执行.