Mysql Mybatis 批量修改数据
Posted chuangsi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql Mybatis 批量修改数据相关的知识,希望对你有一定的参考价值。
Mysql Mybatis 批量修改数据
Mapper
Integer updateListPO(List<ProjectQuotationItemPO> upateList);
方法一:
<update id="updateListPO">
<foreach collection="list" separator=";" item="item">
UPDATE project_quotation_item
SET product_num = #item.productNum,
product_price_total = #item.productPriceTotal,
product_price_wttax = #item.productPriceWttax,
certificate = #item.certificate,
deliver_date = #item.deliverDate,
product_brand = #item.productBrand,
producer = #item.producer,
exp = #item.exp,
is_deleted = #item.isDeleted,
remark = #item.remark,
substitute_type = #item.substituteType,
quotation_status = #item.quotationStatus
WHERE
id = #item.id
</foreach>
</update>
需要在SQL连接的URL添加 allowMultiQueries=true
但是根据不同的Mysql版本或者是其他环境因素,可能还是会执行失败。
方法二:
<update id="updateListPO">
<!-- 优化后的逻辑 -->
update project_quotation_item
<set>
<trim prefix="product_num = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.productNum
</foreach>
</trim>
<trim prefix="product_price_total = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.productPriceTotal
</foreach>
</trim>
<trim prefix="product_price_wttax = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.productPriceWttax
</foreach>
</trim>
<trim prefix="certificate = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.certificate
</foreach>
</trim>
<trim prefix="deliver_date = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.deliverDate
</foreach>
</trim>
<trim prefix="product_brand = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.productBrand
</foreach>
</trim>
<trim prefix="producer = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.producer
</foreach>
</trim>
<trim prefix="exp = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.exp
</foreach>
</trim>
<trim prefix="is_deleted = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.isDeleted
</foreach>
</trim>
<trim prefix="remark = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.remark
</foreach>
</trim>
<trim prefix="substitute_type = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.substituteType
</foreach>
</trim>
<trim prefix="quotation_status = case" suffix="end,">
<foreach collection="list" item="item">
when id=#item.id then #item.quotationStatus
</foreach>
</trim>
</set>
<where>
id in
<foreach collection="list" separator="," item="item" open="(" close=")">
#item.id
</foreach>
</where>
</update>
拼接处的SQL语句
update project_quotation_item
SET product_num = case when id=2203220000003867 then 101
when id=2203220000003868 then 10
when id=2203220000003869 then 20 end,
product_price_total = case when id=2203220000003867 then 1111
when id=2203220000003868 then 220
when id=2203220000003869 then 660 end,
product_price_wttax = case when id=2203220000003867 then 11
when id=2203220000003868 then 22
when id=2203220000003869 then 33 end,
certificate = case when id=2203220000003867 then "11"
when id=2203220000003868 then "22"
when id=2203220000003869 then "33" end,
deliver_date = case when id=2203220000003867 then 11
when id=2203220000003868 then 22
when id=2203220000003869 then 33 end,
product_brand = case when id=2203220000003867 then "11"
when id=2203220000003868 then "22"
when id=2203220000003869 then "33" end,
producer = case when id=2203220000003867 then "11"
when id=2203220000003868 then "22"
when id=2203220000003869 then "33" end,
exp = case when id=2203220000003867 then 11
when id=2203220000003868 then 22
when id=2203220000003869 then 33 end,
is_deleted = case when id=2203220000003867 then 0
when id=2203220000003868 then 0
when id=2203220000003869 then 0 end,
remark = case when id=2203220000003867 then null
when id=2203220000003868 then null
when id=2203220000003869 then null end,
substitute_type = case when id=2203220000003867 then "11"
when id=2203220000003868 then "22"
when id=2203220000003869 then "33" end,
quotation_status = case when id=2203220000003867 then 2
when id=2203220000003868 then 2
when id=2203220000003869 then 2 end
WHERE id in
(
2203220000003867
,
2203220000003868
,
2203220000003869
)
mysql/mybatis 批量新增/删除/修改
1.mybatis相关:
新增:–返回值为增加的的行数
int insertLableBatch(@Param("list")List<UserGroupFilterLabel> list);
<insert id="insertLableBatch" parameterType="com.sf.cps.mana.model.UserGroupFilterLabel">
insert into ti_user_group_filter_label
(emp_group_id,label_type,label_code,label_name,label_symbol,label_content,label_valid,create_name,create_emp,create_time)
values
<foreach collection="list" item="re" separator=",">
(
#{re.empGroupId,jdbcType=INTEGER},
#{re.labelType,jdbcType=VARCHAR},
#{re.labelCode,jdbcType=VARCHAR},
#{re.labelName,jdbcType=VARCHAR},
#{re.labelSymbol,jdbcType=VARCHAR},
#{re.labelContent,jdbcType=VARCHAR},
#{re.labelValid,jdbcType=INTEGER},
#{re.createName,jdbcType=VARCHAR},
#{re.createEmp,jdbcType=VARCHAR},
now()
)
</foreach>
</insert>
修改:使用 分号;拼接语句需要在链接配置上加上 allowMultiQueries=true& 不然会报sql赋值错误;
int updateLableBatch(@Param("list")List<UserGroupFilterLabel> list);
<!--批量修改-跟java循环其实是一样的只是逻辑清晰些-->
<update id="updateLableBatch" parameterType="com.sf.cps.mana.model.UserGroupFilterLabel">
<foreach collection="list" separator=";" item="item">
update ti_user_group_filter_label
<set>
<if test="item.empGroupId != null">
emp_group_id = #{item.empGroupId,jdbcType=INTEGER},
</if>
<if test="item.labelType != null">
label_type = #{item.labelType,jdbcType=VARCHAR},
</if>
<if test="item.labelCode != null">
label_code = #{item.labelCode,jdbcType=VARCHAR},
</if>
<if test="item.labelName != null">
label_name = #{item.labelName,jdbcType=VARCHAR},
</if>
<if test="item.labelSymbol != null">
label_symbol = #{item.labelSymbol,jdbcType=VARCHAR},
</if>
<if test="item.labelContent != null">
label_content = #{item.labelContent,jdbcType=VARCHAR},
</if>
<if test="item.labelValid != null">
label_valid = #{item.labelValid,jdbcType=INTEGER},
</if>
<if test="item.modifyEmp != null">
modify_emp = #{item.modifyEmp,jdbcType=VARCHAR},
</if>
<if test="item.modifyName != null">
modify_name = #{item.modifyName,jdbcType=VARCHAR},
</if>
modify_time = now()
</set>
where id = #{item.id,jdbcType=INTEGER}
</foreach>
</update>
修改/删除(改状态式的删除):–返回值为增加的的行数
int delLableBatch(@Param(“modifyEmp”)String modifyEmp,@Param(“modifyName”)String modifyName, @Param(“list”)List list);
<!--批量删除-->
<update id="delLableBatch">
update ti_user_group_filter_label
<set>
<if test="modifyEmp != null">
modify_emp = #{modifyEmp,jdbcType=VARCHAR},
</if>
<if test="modifyName != null">
modify_name = #{modifyName,jdbcType=VARCHAR},
</if>
modify_time = now(),
label_valid = 0
</set>
where emp_group_id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item,jdbcType=INTEGER}
</foreach>
</update>
2.批处理相关:注意使用批处理需要在链接信息上添加 rewriteBatchedStatements=true 参数
package com.sf.sfim.sync.util;
import com.sf.sfim.sync.model.TabContact;
import com.sf.sfim.sync.source.DynamicDataSourceRegister;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
@Component
public class BatchedStatements {
/**
* 批处理方法
* @param dbName 对应数据源的name
* @param tabContacts
* @return
*/
@SuppressWarnings("all")
public int updateContactBatche(String dbName, List<TabContact> tabContacts) {
Connection conn = null;
PreparedStatement pst = null;
try {
//数据源获取,此处使用动态数据源
Class.forName("com.mysql.jdbc.Driver");
if (StringUtils.isNotEmpty(dbName)) {
conn = DynamicDataSourceRegister.slaveDataSources.get("dbName").getConnection();
} else {
conn = DynamicDataSourceRegister.defaultDataSource.getConnection();
}
//拼接逻辑
String sql = "update tab_contact set col_create_time = ? where col_account = ?";
pst = conn.prepareStatement(sql);
for (int loop = 0; loop < tabContacts.size(); loop++) {
pst.setDate(1, new Date(System.currentTimeMillis()));
pst.setString(2, tabContacts.get(loop).getColAccount());
pst.addBatch();
}
//执行和返回值的处理
int[] result = pst.executeBatch();
int sum = 0;
for (int i : result) {
sum = sum + i;
}
return sum;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return 0;
}
}
3.使用insert or update 方案:(有2种方案)
int saveOrUpdateBatch(@Param("list")List<Project> list);
<insert id="saveOrUpdateBatch">
insert into project
(code, org_code,org_name, source, create_time,version, rpt_date)
values
<foreach collection="list" item="re" separator=",">
(
#{re.code,jdbcType=VARCHAR},
#{re.orgCode,jdbcType=VARCHAR},
#{re.orgName,jdbcType=VARCHAR},
#{re.source,jdbcType=VARCHAR},
#{re.createTime,jdbcType=BIGINT},
#{re.version,jdbcType=VARCHAR},
CURRENT_DATE()
)
</foreach>
ON DUPLICATE KEY UPDATE
code = VALUES(code),
name = VALUES(name),
org_code = VALUES(org_code),
org_name = VALUES(org_name),
source = VALUES(source),
create_time = VALUES(create_time),
version = VALUES(version),
rpt_date = VALUES(rpt_date)
</insert>
<insert id="saveOrUpdate" parameterType="com.sf.sfim.task.model.Project" keyProperty="projectId" useGeneratedKeys="true">
<selectKey keyProperty="count" order="BEFORE" resultType="java.lang.Integer">
select count(1) as count from project where code = #{code,jdbcType=VARCHAR}
</selectKey>
<!-- 如果大于0则更新 -->
<if test="count>0">
update project
set name = #{projectName,jdbcType=VARCHAR},
org_code = #{orgCode,jdbcType=VARCHAR},
org_name = #{orgName,jdbcType=VARCHAR},
source = #{source,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=BIGINT},
version = #{version,jdbcType=VARCHAR},
rpt_date = #{rptDate,jdbcType=DATE}
where code = #{code,jdbcType=VARCHAR}
</if>
<!-- 如果等于0则新增 -->
<if test="count==0">
insert into project (code, name, org_code,
org_name, source, create_time,
version, rpt_date)
values (#{code,jdbcType=VARCHAR}, #{projectName,jdbcType=VARCHAR}, #{orgCode,jdbcType=VARCHAR},
#{orgName,jdbcType=VARCHAR}, #{source,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT},
#{version,jdbcType=VARCHAR}, #{rptDate,jdbcType=DATE})
</if>
</insert>
4.多insert/update处理:注意使用批处理需要在链接信息上添加 rewriteBatchedStatements=true 参数
void overdueTaskCalculate(@Param("calculateTime") Long calculateTime);
<insert id="overdueTaskCalculate">
<!--项目逾期增加-->
insert into user_project_task_report (user_id,user_name,company_id,project_id,overdue)
select tu.user_id,tu.user_name,t.company_id,t.project_id,count(tu.user_id) overdue
from task t inner join task_user tu on t.id = tu.task_id where t.expect_end_time > 0
and t.expect_end_time < #{calculateTime} and t.status in (1,2) and t.del_status = 0
and t.overdue_status = 0 and t.project_id > 0 and tu.del_status = 0 and tu.type in(1,3)
group by tu.user_id,t.project_id
ON DUPLICATE KEY UPDATE overdue=overdue+VALUES(overdue);
<!--任务逾期增加-->
insert into user_task_report (user_id,user_name,company_id,overdue)
select tu.user_id,tu.user_name,t.company_id,count(tu.user_id) overdue
from task t inner join task_user tu on t.id = tu.task_id where t.expect_end_time > 0
and t.expect_end_time < #{calculateTime} and t.status in (1,2) and t.del_status = 0
and t.overdue_status = 0 and tu.del_status = 0 and tu.type in(1,3)
group by tu.user_id
ON DUPLICATE KEY UPDATE overdue=overdue+VALUES(overdue);
<!--任务逾期状态更改-->
update task set overdue_status = 1,update_time = #{calculateTime} where expect_end_time > 0
and expect_end_time < #{calculateTime} and overdue_status = 0 and status in (1,2) and del_status = 0;
</insert>
以上是关于Mysql Mybatis 批量修改数据的主要内容,如果未能解决你的问题,请参考以下文章