oracle sql&mybatis 防止重复插入(实现唯一性约束)

1.如表ROLE如下所示:

表 ROLE

IDROLE_NAME
1user
2admin

字段ROLE_NAME在插入或者更新时需要避免数据重复,不选择在表上加unique约束是因为数据迁移可能因为unique约束造成问题,因此选择在sql层面实现。

2.oracle sql

①插入

INSERT INTO ROLE ("ROLE_NAME") SELECT 'user' FROM dual WHERE NOT EXISTS (select 1 from ROLE where ROLE_NAME = 'user');

②更新

update ROLE SET "ROLE_NAME"='user' WHERE not EXISTS (select 1 from ROLE where ROLE_NAME = 'user' AND ID <> 1) and ID = 1;

在sql中做某个字段唯一性校验时,最好给该字段建个索引提高效率。

3.mybatis

①插入

  <insert id="insertSelective" parameterType="com.portal.entity.Role" >
    insert into ROLE
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="roleName != null and roleName !=''" >
        ROLE_NAME,
      </if>
    </trim>
        select
    <trim suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=DECIMAL},
      </if>
      <if test="roleName != null and roleName !=''" >
        #{roleName,jdbcType=VARCHAR},
      </if>
    </trim> from dual
    where not exists
    (select 1 from ROLE where ROLE_NAME = #{roleName,jdbcType=VARCHAR})
  </insert>

②更新

<update id="update" parameterType="map">
        update "ROLE"
        <set>
            <if test="role.roleName != null and role.roleName !=''">
                ROLE_NAME=#{role.roleName},
            </if>
        </set>
        WHERE not EXISTS
        (select 1 from ROLE where ROLE_NAME = 'user' AND ID &lt; &gt; #{Id}) and ID = #{Id}
    </update>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值