Mysql selectKey的使用,新增当天数据不重复

本文讲述了在项目中如何利用Mybatis的selectKey解决插入数据时主键自动生成问题的一个bug。通过在更新操作前查询特定条件下的记录数,根据查询结果决定是否执行插入操作,确保数据的准确性和一致性。
摘要由CSDN通过智能技术生成
selectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。但是最近项目中修改了同事的一个bug,通过selectKey解决的。内容如下
    @TableField(exist = false)
    private int count;
 <!--新增-->
    <update id="insertBatchFor" parameterType="com.ct.business.domain.DeductionRecordEntity">
        <!--查看是否已经修改成功,修改成功了则修改,否则不修改-->
        <selectKey keyProperty="count" order="BEFORE" resultType="int" >
            select count(1) as count  from tb_deduction_record where user_id = #{userId} AND trade_type =  #{tradeType}
            and type = #{type} and DATE_FORMAT(create_time,'%Y-%m-%d') = DATE_FORMAT(#{createTime},'%Y-%m-%d')
        </selectKey>

        <!--如果等于null新增-->
        <if test="count==0 ">
            INSERT INTO tb_deduction_record (id, user_id, user_name, user_phone, business_id, amount, reason, create_by, create_time, trade_type, type, site_id)
            values (#{id},#{userId},#{userName},#{userPhone},#{businessId},#{amount},#{reason},#{createBy},#{createTime},#{tradeType},#{type},#{siteId})
        </if>

        <if test="count !=0 ">
            select 1 as count from dual
        </if>

    </update>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值