开发中,经常会遇到向数据库中插入数据,如果数据库中执行存在这条记录就更update操作,如果不存在就执行insert操作。当操作一条数据的时候,实现比较简单,比较笨的方法(小编之前自己就是用这种方法)就是先根据主键或者唯一键进行查询,如果查到数据库总有记录,就执行update,如果没有查到记录,就执行insert。Mysql有一个自己特有的关键词-on duplicate key update,很容易理解,就是遇到重复的唯一键时执行更新。 这种方法只会与数据库交互一次,比第一种要快。但是在操作批量数据的时候,显然第一种用起来就不太实际了,可以用第二种方式批量操作。
单条数据中使用 on duplicate key update
<insert id="save" parameterType="java.util.List">
insert into
bud_fmr (
project_guid,
unit_guid,
year,
fmr,
rent_unit_price,
management_unit_price,
generalize_unit_price,
taking_unit_price,
remark,
unit_type,
creator_id,
creator_name,
create_time,
updator_id,
updator_name,
update_time)
values
(#{item.projectGuid},
#{item.unitGuid},
#{item.year},
#{item.fmr},
#{item.rentUnitPrice},
#{item.managementUnitPrice},
#{item.generalizeUnitPrice},
#{item.takingUnitPrice},
#{item.remark},
#{item.unitType},
#{item.creatorId},
#{item.creatorName},
#{item.createTime},
#{item.updatorId},
#{item.updatorName},
#{item.updateTime})
on duplicate key update
fmr = values(fmr),
rent_unit_price = values(rent_unit_price),
management_unit_price = values(management_unit_price),
generalize_unit_price = values(generalize_unit_price),
taking_unit_price = values(taking_unit_price),
updator_id = values(creator_id),
updator_name=values(creator_name),
update_time = values(create_time)
</insert>
批量操作数据的业务,单纯的批量新增和批量插入之前已经有写过怎么去实现。有的时候,还会遇到批量的插入数据,其中一部分数据库中已经存在相关的记录,一部分是没有存在的,我们想将存在的数据进行更新,不存在的数据进行插入。实现方法
<insert id="save" parameterType="java.util.List">
insert into
bud_fmr (
project_guid,
unit_guid,
year,
fmr,
rent_unit_price,
management_unit_price,
generalize_unit_price,
taking_unit_price,
remark,
unit_type,
creator_id,
creator_name,
create_time,
updator_id,
updator_name,
update_time)
values
<foreach collection="list" separator="," item="item">
(
#{item.projectGuid},
#{item.unitGuid},
#{item.year},
#{item.fmr},
#{item.rentUnitPrice},
#{item.managementUnitPrice},
#{item.generalizeUnitPrice},
#{item.takingUnitPrice},
#{item.remark},
#{item.unitType},
#{item.creatorId},
#{item.creatorName},
#{item.createTime},
#{item.updatorId},
#{item.updatorName},
#{item.updateTime}
)
</foreach>
on duplicate key update
fmr = values(fmr),
rent_unit_price = values(rent_unit_price),
management_unit_price = values(management_unit_price),
generalize_unit_price = values(generalize_unit_price),
taking_unit_price = values(taking_unit_price),
updator_id = values(creator_id),
updator_name=values(creator_name),
update_time = values(create_time)
</insert>
使用中注意事项:
on duolicate key update后为执行的更新操作,更新时,数据库的字段等于values括号内的字段,不在是对象的属性值。