最近工作上遇到很多批量插入的场景,但是百度很难得到我想要的结果,而且查出来的效果不是很好~ 所以就自己来写一份给大家参考,希望对大家有用
@Insert("<script> INSERT INTO t_device_policy "
+ "(id,device_id,type,policy,create_time,update_time) "
+ "VALUES "
+ "<foreach collection = 'list' item='list' separator=',' > "
+ " (#{list.id},#{list.deviceId},#{list.policyType},#{list.policy},#{list.createTime},#{list.updateTime}) "
+ "</foreach>"
+ "</script>")
int insert(@Param(value = "list")List<DevicePolicy> list);
复制代码
@Insert("<script> INSERT INTO t_device_policy "
+ "(id,device_id,type,policy "
+ "VALUES "
+ "<foreach collection = 'list' item='list' separator=',' > "
+ " (#{list.id},#{list.deviceId},#{list.policyType},#{list.policy}) "
+ "</foreach>"
+ "ON DUPLICATE KEY "
+ "UPDATE policy = VALUES(policy)"
+ "</script>")
int insert(@Param(value = "list")List<DevicePolicy> list);
复制代码
ON DUPLICATE KEY的使用场景大家知道吗?
当你设计的数据库表中的主键存在时更新对应的字段,不存在则插入。
还有一种情况就是你设计的唯一主键存在时更新对应的字段,不存在则插入。
大家可以根据自己的场景看是否需要该字段~
@Update({"<script>" +
"<foreach collection=/"list/" item=/"item/" separator=/";/">" +
" UPDATE t_student" +
" <set> " +
" c_state = #{item.State}, " +
" </set>" +
" <where> " +
" c_id = #{item.id} " +
" </where>" +
" </foreach> " +
"</script>"})
void updateStudentState(@Param(value = "list") List<Student> list);
复制代码
<insert id="batchAdd" parameterType="java.util.List">
INSERT INTO t_student(uid,student_id,study_days)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.uid},#{item.studentId},#{item.studyDays})
</foreach>
</insert>
复制代码
Mapper中的方法为
void batch(List<StudentPo> po) 复制代码
<insert id="batchAdd" parameterType="java.util.List">
INSERT INTO t_student(uid,student_id,study_days)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.uid},#{item.studentId},#{item.studyDays})
</foreach>
ON DUPLICATE KEY UPDATE
update_time = now()
</insert>
复制代码
Mapper中的方法为
void batch(List<StudentPo> po) 复制代码
以上为Mybatis批量操作经常使用的部分,大家可以根据需要自行提取,如果有什么问题可以留言哈~