mybatis实现hibernate中的saveOrUpdate方法

mybatis实现saveOrUpdate

最近在做项目过程中遇到需要更新或者插入的问题,就想起hibernate有个saveOrUpdate的方法,想着mybatis是不是也有这个方法。于是上网查找资料。该问题有两种解决方案。

方法1:使用mybatis的标签

<insert id="saveOrUpdate" >
  <selectKey keyProperty="count" resultType="int" order="BEFORE">
    select count(*) from station where id = #{id}
  </selectKey>
  <if test="count > 0">
    update station 
    set s_describe = #{sDescribe},s_longitude = #{sLongitude} 
    where id = #{id}
  </if>
  <if test="count==0">
    insert into station values(#{id},#{sDescribe},#{sLongitude})
  </if>
</insert>

这种方式实际上就是将需求拆为两条sql语句来完成,虽然解决问题了,但是感觉不利于事务的控制管理

方式2:使用sql语句实现

通过这次遇到的问题,我也学到了原生sql语句是怎么实现这个功能的。
在mysql里,如果在INSERT语句末尾指定了ON DUPLICATE KEY UPDATE,并且插入行后会导致在一个UNIQUE索引或PRIMARY KEY中出现重复值,则在出现重复值的行执行UPDATE;如果不会导致唯一值列重复的问题,则插入新行。

INSERT INTO table (a,c) VALUES (1,3) ON DUPLICATE KEY UPDATE c=c+1;
UPDATE TABLE SET c=c+1 WHERE a=1;

假设a为unique索引,当执行如上语句,如果出现已经存在a=1的数据,则执行该语句的结果为c=4即执行后面的update,c=c+1。

所以最后我决定还是用第二种方式:

<insert id="saveOrUpdate" parameterType="com.buoy.entity.Station">
    INSERT INTO station
            (s_id,
             s_describe,
             s_station,
             s_buoyid)
    VALUES (
            #{sId,jdbcType=INTEGER}, 
            #{sDescribe,jdbcType=VARCHAR},
            #{sStation,jdbcType=VARCHAR},
            #{sBuoyid,jdbcType=VARCHAR}
            )
    ON DUPLICATE KEY UPDATE 
             <if test="date != null">
                 date = #{date,jdbcType=VARCHAR},
             </if>
                 s_longitude = #{sLongitude,jdbcType=VARCHAR},
                 s_latitude = #{sLatitude,jdbcType=VARCHAR},
             <if test="sDescribe != null">
                s_describe = #{sDescribe,jdbcType=VARCHAR},
             </if>
             s_station = #{sStation,jdbcType=VARCHAR},
             ;
  </insert>

猜你喜欢

转载自blog.csdn.net/liao0801_123/article/details/82987245