mapper的批量操作 批量更新mysql 批量删除、插入、更新插入(ON DUPLICATE KEY UPDATE)
mysql的一些批量操作,mapper文件中的一些写法,其中使用的sys_user表中有id(自增),name ,address,phone字段。
批量删除
思路: 将数组拆分为单个数据. 可以通过遍历的方式操作
语法: mybatis为了参数取值方便,特意封装了遍历的标签 foreach
关于标签参数说明:
1.如果传递的参数是数组, 则collection=“array”
2.如果传递的参数是list集合, 则collection=“list”
3.如果传递的参数是Map集合, 则collection=“map中的key”
标签属性说明:
1.collection 集合的名称
2.item 每次遍历的数据的形参变量
3.open 循环的开始标签
4.close 循环的结束标签
5.index 循环遍历下标 一般不用
6.separator 循环遍历的分割符
具体内容如下:
<delete id="deleteIds">
delete from sys_user where id in (
<foreach collection="array" item="id" separator=",">
#{id}
</foreach
)
</delete>
使用注释的方式:
@delete({"delete from sys_user id in(
<foreach collection="array" item="id" separator=",">
#{id}
</foreach>)"})
int delete(@Param("array") List<String> list);
批量更新
<update id="update">
update sys_usert
<set>
<if test="name!= null">
name= #{name},
</if>
<if test="address!= null">
address= #{address},
</if>
<if test="phone != null">
phone = #{phone },
</if>
</set>
where id in (
<foreach collection="array" item="id" separator=",">
#{id}
</foreach
)
</update>
注意:如果更新数据全的话,可以使用这种方式,不全的话建议使用on duplicate key update
批量插入
<insert id="saveUser" parameterType="java.util.List">
insert into sys_user(name,address,phone) values
<foreach collection="list" index="index" item="item" separator=",">
(#{item.name},#{item.address},#{item.phone})
</foreach>
</insert>
批量更新插入(on duplicate key update:当表中没有原来记录时,就插入,有的话就更新)
批量更新name字段值
具体实现如下:
INSERT INTO sys_user(name,address,phone)
VALUES (#{name},#{address},#{phone})
ON DUPLICATE KEY UPDATE
name=values(name)
使用注释的方式:
@Insert("INSERT INTO sys_user(name,address,phone) VALUES " +
"(#{name},#{address},#{phone})" +
" ON DUPLICATE KEY UPDATE name=#{name},phone=#{phone}")
int save(SysUser sysUser);