逻辑:如果数据库里有,则进行更新操作,如果没有则插入数据。
这里的insert可以不用写字段
sql
merge INTO table_name a using ( SELECT count( field01) co FROM table_name WHERE field01 = '123456' ) b ON ( b.co <> 0 )
WHEN MATCHED THEN
UPDATE
SET field02 = 'update'
WHERE
field01 = '123456'
WHEN NOT matched THEN
INSERT
VALUES
( '123456', 'insert' )
这里事务要自己提交一下,不然就会卡死
java
//事务的一些基础信息,如超时时间、隔离级别、传播属性等
@Resource
private TransactionDefinition transactionDefinition;
//事务管理器
@Resource
private PlatformTransactionManager platformTransactionManager;
@Override
public Json saveServiceImpl(Entity entity) {
//TransactionStatus:事务的一些状态信息,如是否是一个新的事务、是否已被标记为回滚
TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
try {
int count = this.baseMapper.saveMapper(entity);
System.out.println("事务提交前:" + count);
platformTransactionManager.commit(transaction);
System.out.println("事务已提交:" + count);
} catch (Exception e) {
e.printStackTrace();
platformTransactionManager.rollback(transaction);
return Json.error("保存失败" + e.getMessage(), null, 500);
}
return Json.success(1);
}
xml写法(注意:条件字段{field01}不能被更新)
xml
<insert id="saveMapper" parameterType="com.azure.entity.Entity ">
merge INTO table_name using (SELECT count(1) coun
FROM table_name
WHERE field01 = #{field01,jdbcType=VARCHAR}) b ON (b.coun > 0)
WHEN NOT matched THEN
INSERT (field01, field02)
VALUES (#{field02,jdbcType=VARCHAR},
#{field03,jdbcType=VARCHAR})
WHEN matched THEN
UPDATE
<trim prefix="set" suffixOverrides=",">
<if test="field02 != null and field02 != ''">
a.field02 = #{field02,jdbcType=VARCHAR},
</if>
<if test="field03 != null and field03 != ''">
a.field03 = #{field03,jdbcType=VARCHAR},
</if>
</trim>
</insert>