mybatis saveOrUpdate 保存或更新\replace into

6 篇文章 0 订阅

类似于hibernate,mybatis也可以实现保存或更新:

<insert id="saveOrUpdateByActId" parameterType="com.ai.rai.interests.operation.entity.beans.TdCoAct">
    <selectKey keyProperty="count" resultType="int" order="BEFORE">
      select count(*) from TD_CO_ACT where act_id = #{actId}
    </selectKey>
    <if test="count > 0">
      update TD_CO_ACT
      set act_rule = #{actRule}
      where act_id = #{actId}
    </if>
    <if test="count==0">
      insert into TD_CO_ACT (act_id,start_date,end_date,act_rule,act_status) values(#{actId},NOW(),NOW(),#{actRule},2)
    </if>
  </insert>

 

直接用吧

 

可能会报错,比如:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL 

这个时候只要检查下表有没有建,sql语句有没有问题,xml配置有没有问题,

一般没什么大问题;

仅供参考

2019.2.22新增:

记录之前看到的一种避免插入数据时主键冲突的解决方案:

MySQL的:replace into

用法:

REPLACE INTO test(title,uid) VALUES ('1234657','1001');

[SQL]REPLACE INTO test(title,uid) VALUES ('1234657','1001');
受影响的行: 2
时间: 0.140s

这里插入的数据在表中时存在的,uid是唯一索引;

(//todo   如果不是唯一的会不会有影响,这个没有试)

可以看到是做了两次操作,即先删除再插入,

详细参考:

https://www.cnblogs.com/c-961900940/p/6197878.html

https://www.jb51.net/article/54345.htm

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值