Mybatis实现批量插入(存在则更新,不存在则插入数据)有两种情况,一种情况是没有唯一索引,一种是有唯一索引。两种情况的实现方法如下。
没有唯一索引
1
2
3
4
5
6
7
8
9
|
<insert id="saveOrUpdate2" >
<select count(*) as count from user where id = #{id} for update</select>
<if test="count > 0">
update user set age = #{age}, name = #{name} where id = #{id}
</if>
<if test="count == 0">
insert into user (age, name) values (#{age}, #{name})
</if>
</insert>
|
有唯一索引
唯一索引为name
1
2
3
4
5
6
7
|
<insert id="insertOrUpdateUser" parameterType="User">
INSERT INTO user (name, age, email)
VALUES (#{name}, #{age}, #{email})
ON DUPLICATE KEY UPDATE
age = VALUES(age),
email = VALUES(email);
</insert>
|