当前位置: 代码迷 >> 综合 >> mybatis saveOrUpdate 保存或更新\replace into
  详细解决方案

mybatis saveOrUpdate 保存或更新\replace into

热度:97   发布时间:2024-01-17 22:35:42.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_ACTset 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

  相关解决方案