代码如下,插入前会判断是否存在,不存在才会插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<insert id="insertSelectiveIsNotExist">
<selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO account
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="status != null">
status,
</if>
<if test="remark != null">
remark,
</if>
</trim>
<trim prefix="SELECT " suffix="" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updTime != null">
#{updTime,jdbcType=TIMESTAMP},
</if>
<if test="status != null">
#{status,jdbcType=CHAR},
</if>
<if test="remark != null">
#{remark,jdbcType=VARCHAR},
</if>
</trim>
FROM DUAL
WHERE NOT EXISTS(
SELECT count(*) FROM user WHERE id = #{userId,jdbcType=VARCHAR}
) LIMIT 1
</insert>

我觉得这种做法只是相对保险,要想确保绝对上的唯一,一定要加上唯一约束.