溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mybatis中selectKey有什么用

發(fā)布時間:2022-01-25 10:44:43 來源:億速云 閱讀:296 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)mybatis中selectKey有什么用的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

mybatis的selectKey作用

當(dāng)我們使用id自增操作Mybatis時,需要返回最新插入的id的話,可以進行如下操作:

<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS ID 
</selectKey>

在insert中添加即可:

<insert id="insert" parameterType="com.pinyougou.pojo.TbGoods" >
    <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
      SELECT LAST_INSERT_ID() AS id
    </selectKey>
    insert into tb_goods (id, seller_id, goods_name,
      default_item_id, audit_status, is_marketable, 
      brand_id, caption, category1_id, 
      category2_id, category3_id, small_pic, 
      price, type_template_id, is_enable_spec, 
      is_delete)
    values (#{id,jdbcType=BIGINT}, #{sellerId,jdbcType=VARCHAR}, #{goodsName,jdbcType=VARCHAR}, 
      #{defaultItemId,jdbcType=BIGINT}, #{auditStatus,jdbcType=VARCHAR}, #{isMarketable,jdbcType=VARCHAR}, 
      #{brandId,jdbcType=BIGINT}, #{caption,jdbcType=VARCHAR}, #{category1Id,jdbcType=BIGINT}, 
      #{category2Id,jdbcType=BIGINT}, #{category3Id,jdbcType=BIGINT}, #{smallPic,jdbcType=VARCHAR}, 
      #{price,jdbcType=DECIMAL}, #{typeTemplateId,jdbcType=BIGINT}, #{isEnableSpec,jdbcType=VARCHAR}, 
      #{isDelete,jdbcType=VARCHAR})
  </insert>

然后操作int newId = goodsMapper.insert(goods.getGoods()); 就能拿到最新加入的ID信息了 

mybatis selectKey 失效問題踩坑

  • selectKey 會將 SELECT LAST_INSERT_ID()的結(jié)果放入到傳入的實體類的主鍵里面,

  • keyProperty對應(yīng)的實體類中的主鍵的屬性名,這里是 實體類中的id,因為它跟數(shù)據(jù)庫的主鍵對應(yīng)order

  • AFTER 表示 SELECT LAST_INSERT_ID() 在insert執(zhí)行之后執(zhí)行,多用與自增主鍵,

  • BEFORE 表示 SELECTLAST_INSERT_ID() 在insert執(zhí)行之前執(zhí)行,這樣的話就拿不到主鍵了,這種適合那種主鍵不是自增的類型

resultType 主鍵類型

<insert id="insertCheckGroup"  parameterType="com.zyl.pojo.CheckGroup">
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into check_group (name) value (#{name});
</insert>

當(dāng)使用了selectkey時 Dao接口請勿使用@Param 映射注解,會導(dǎo)致selectKey標(biāo)簽失效

int insertCheckGroup(CheckGroup checkGroup);

如果傳多個參數(shù)需使用@Param時

int insertCheckGroup(@Param("test") CheckGroup checkGroup);

xml標(biāo)簽keyProperty對應(yīng)主鍵名稱時應(yīng)加上test.

<insert id="insertCheckGroup"  parameterType="com.zyl.pojo.CheckGroup">
        <selectKey resultType="int" keyProperty="test.id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into check_group (name) value (#{name});
</insert>

感謝各位的閱讀!關(guān)于“mybatis中selectKey有什么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI