当前位置:   article > 正文

selectKey获取最新操作的主键id,支持高并发_selectkey 并发

selectkey 并发

描述

有时候操作数据库的时候我们对某个表插入一条记录的时候,记录的主键是一个自增序号id。(因此没有插入id,一般也不用知道id)
但是插入成功后我们又要那个id来做另一些dao操作,比如插入这个id作为外键的关系表记录。想要获取这个id就很麻烦了,而且数据库操作并发量很多, 就很多意外了。
因此MyBatis提供了一个简单的<selectKey>获取最新id, 而且有针对用户的同步锁。

实现

    <insert id="insertTransaction" parameterType="transaction">
        INSERT INTO tb_transaction(order_id, book_id, book_name, store_id, store_name, customer_id,
              customer_name, customer_phone, customer_address, price, time, remark, book_img_url)
              VALUES (#{orderId}, #{bookId}, #{bookName}, #{storeId}, #{storeName}, #{customerId},
              #{customerName}, #{customerPhone}, #{customerAddress}, #{price}, #{time}, #{remark}, #{bookImgUrl})
    </insert>

    <insert id="insertStoreTransactionRelation" parameterType="storeTransactionRelation">
        <!-- 获取到的最新修改id添加到storeTransactionRelation的transactionId上 -->
        <selectKey resultType="integer" keyProperty="transactionId" order="BEFORE">
            SELECT LAST_INSERT_ID() AS  transactionId
        </selectKey>
        INSERT INTO tb_store_transaction VALUES (#{storeId}, #{transactionId})
    </insert>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

keyProperty改为要最新的id保存到的变量名,这里是StoreTransactionRelation这个POJO的transactionId属性。
order="BEFORE"表示插入前获取替换。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/241399
推荐阅读
相关标签
  

闽ICP备14008679号