MyBatis Implementation Saveorupdate
Recently in the process of doing the project to meet the need to update or insert the problem, I think of hibernate has a saveorupdate method, think MyBatis is not also have this method. So the Internet to find information. There are two solutions to this problem. Method 1: Use the MyBatis label
<insert id= "Saveorupdate" >
<selectkey keyproperty= "Count" resulttype= "int" order= "before" >
Select COUNT (*) from station where id = #{id}
</selectKey>
<if test= "Count > 0" >
update statio n
Set s_describe = #{sdescribe},s_longitude = #{slongitude}
where id = #{id}
</if>
<if test= " Count==0 ">
insert INTO station VALUES (#{id},#{sdescribe},#{slongitude})
</if>
</insert >
This approach is actually the need to split the requirements into two SQL statements to complete, although solve the problem, but it is not conducive to the management of transaction control mode 2: Using SQL statement Implementation
Through this encounter problem, I also learned how the native SQL statement is how to achieve this function.
In MySQL, if an on DUPLICATE KEY UPDATE is specified at the end of the INSERT statement and the row is inserted causing duplicate values in a unique index or primary KEY, the UPDATE is performed on the row where the duplicate value occurs Insert a new row if the problem does not cause a duplicate of the unique value column.
INSERT into table (a,c) VALUES (1,3) on DUPLICATE KEY UPDATE c=c+1;
UPDATE TABLE SET c=c+1 WHERE a=1;
Assuming that a is a unique index, when you execute the above statement, if the data that already exists a=1 is present, the result of executing the statement is c=4, which executes the subsequent update,c=c+1.
So finally I decided to use the second way:
<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,jdbctyp
E=varchar}, S_latitude = #{slatitude,jdbctype=varchar}, <if test= "Sdescribe! = null" > S_describe = #{sdescribe,jdbctype=varchar}, </if> s_station = #{sstation,j
Dbctype=varchar},; </insert>