Mysql saveOrUpdate

在项目的开发中,经常会遇到这样的场景,有一些数据在写入的时候如果数据库里面已经存在这条数据的时候,就进行更新操作,如果数据库里面不存在这条数据,我们就新增。

mysql中的saveOrUpdate是根据唯一索引来判断的,如果有这个数据则进行更新,没有则新增

 

一、单条数据的新增或更新

<insert id="saveOrUpdate" parameterType="TestVo">

insert into table_name (

col1, col2, col3 )

values(

#{field1},

#{field2},

#{field3} )

on duplicate key update

col1 = #{field1},

col2 = #{field2},

col3 = #{field3}

</insert>

 

 

二、多条数据的新增或更新

<insert id="batchSaveOrUpdate" parameterType="java.util.List">

insert into table_name (

col1, col2, col3 )

<foreach collection="list" item="item" index="index" separator=",">

values(

#{item.field1},

#{item.field2},

#{item.field3} )

</foreach>

on duplicate key update

col1 = VALUES (col1),

col2 = VALUES (col2),

col3 = VALUES (col3)

</insert>

 

posted @ 2017-05-20 21:59  javaeelwh  阅读(1096)  评论(0)    收藏  举报