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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/84669590

描述

有时候操作数据库的时候我们对某个表插入一条记录的时候,记录的主键是一个自增序号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>

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

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/84669590
今日推荐