Mybatis批量添加、批量修改
Mybatias中批量添加功能实现
提示:以下是本篇文章正文内容,下面案例可供参考
- Mapper层
/**
* @Description: 新增人员信息
* @Param:
* @return:
* @Author: 杨永卓
* @Date: 2022/7/7 20:21
*/
boolean insertUser(@Param("users") List<User> users);
- Mapper.xml中
<insert id="insertUser" parameterType="List">
insert into t_user
(
id,
user_name,
password,
age
)
values
<foreach collection="users" item="user" separator=",">
(
#{user.id},
#{user.userName},
#{user.password},
#{user.age}
)
</foreach>
</insert>
Mybatias中批量修改功能实现
批量修改分为两种,一种需要在application.yml的jdbc配置后面拼接allowMultiQueries=true,第二种不需要。
下面是示例
批量处理的时候需要在jdbc连接后面加上:allowMultiQueries=true,因为默认是不支持批处理的。
第一种
- Mapper层
/**
* 修改人员信息
*
* @param updateList
* 更新集合
* @return {@code Integer}
*/
boolean updateUsers(@Param("list") List<User> updateList);
- Mapper.xml中
<update id="updateUsers" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update t_user
<set>
<if test="item.userName!= null and item.userName!= ''">user_name=#{item.userName},</if>
<if test="item.password!= null and item.password!= ''">password=#{item.password},</if>
<if test="item.age!= null and item.age!= ''">age=#{item.age}</if>
create_date= sysdate()
</set>
where id= #{item.id}
</foreach>
</update>
第二种
- Mapper层
/**
* 批量更新
* @param updateList
* @return
*/
Boolean updateBatch(List<VisualizeDsVideoInfo> updateList);
- Mapper.xml中 通过when then来修改
<!--批量修改-->
<update id="updateBatch" parameterType="java.util.List">
update ds_video
<trim prefix="set" suffixOverrides=",">
<trim prefix = "status=case" suffix="end,">
<foreach collection="list" item="info" index="index">
when id = #{info.id} then #{info.status}
</foreach>
</trim>
<trim prefix = "code=case" suffix="end,">
<foreach collection="list" item="info" index="index">
when id = #{info.id} then #{info.code}
</foreach>
</trim>
<trim prefix = "camera_name=case" suffix="end,">
<foreach collection="list" item="info" index="index">
when id = #{info.id} then #{info.cameraName}
</foreach>
</trim>
<trim prefix = "update_by=case" suffix="end,">
<foreach collection="list" item="info" index="index">
when id = #{info.id} then #{info.updateBy}
</foreach>
</trim>
<trim prefix = "update_time=case" suffix="end,">
<foreach collection="list" item="info" index="index">
when id = #{info.id} then #{info.updateTime}
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="info" index="index">
id = #{info.id}
</foreach>
</update>