mybatis实现saveorupdate

Mybatis实现saveOrUpdate主要在于selectKey的使用,不懂可以详细看下mybatis的教程selectKey部分,看下列代码,实现思路都知道~

主要是selectKey的使用。

count是表结构中的一个属性,并不是临时变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<insert id="saveOrUpdate" >
<selectKey keyProperty="count" resultType="int" order="BEFORE">
select count(*) from user where email = #{email}
</selectKey>
<if test="count > 0">
update user
set auth_code = #{authCode}
where email = #{email}
</if>
<if test="count==0">
INSERT INTO user(email, auth_code, count)
VALUE (#{email},#{authCode},#{count})
</if>
</insert>