溫馨提示×

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

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

Mybatis怎么獲取最新插入數(shù)據(jù)的id

發(fā)布時(shí)間:2022-01-15 11:23:28 來源:億速云 閱讀:207 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹Mybatis怎么獲取最新插入數(shù)據(jù)的id,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

獲取最新插入數(shù)據(jù)的id

原始方法

讀取最后一條的插入數(shù)據(jù),但這樣會(huì)造成如果兩條數(shù)據(jù)同時(shí)插入,會(huì)并發(fā)出現(xiàn)錯(cuò)誤

SELECT * FROM admin_users where 1=1 ORDER BY id desc  LIMIT 1
select MAX(id) from admin_users

使用useGeneratedKeys

useGeneratedKeys 取值范圍true|false 默認(rèn)值是:false。

含義:設(shè)置是否使用JDBC的getGenereatedKeys方法獲取主鍵并賦值到keyProperty設(shè)置的領(lǐng)域模型屬性中。

直接在注冊(cè)完成后取id就行

<!--表名-->
    <sql id="tableName">IMS_BS_BOOK_COPY</sql>
    <!--字段-->
    <sql id="insertField">PRICE,ENTITY_ID,CODE,ADD_TIME,STATUS,REASON,GRID_CODE,STALL_CODE,CASE_CODE,ORDER_CODE</sql>
    <!--字段值-->
    <sql id="insertFieldValue">#{PRICE},#{ENTITY_ID},#{CODE},#{ADD_TIME},#{STATUS},#{REASON},#{GRID_CODE},#{STALL_CODE},#{CASE_CODE},#{ORDER_CODE}</sql>
    <!--新增-->
    <insert id="save" parameterType="pd" useGeneratedKeys="true" keyProperty="id">insert into
        <include refid="tableName"/>(
        <include refid="insertField"/>) values (
        <include refid="insertFieldValue"/>)
    </insert>

根據(jù)時(shí)間查詢最新一條數(shù)據(jù)

第一種的xml配置根據(jù)最新的插入時(shí)間

<select id="selectLast" resultMap="BaseResultMap" parameterType="java.lang.String">
        SELECT
        *
        from 表名
        where createtime=(select max(createtime) from 表名 where
        字段名=#{參數(shù)名,jdbcType=VARCHAR} )
    </select>

第二種的xml配置根據(jù)ownum

select id="selectLast" resultMap="BaseResultMap" parameterType="java.lang.String">
            select t.*,rownum from
            (select * from 表名  where  字段名=#{參數(shù)名,jdbcType=VARCHAR} 
            order by createtime desc)t   where rownum=1
    </select>

以上是“Mybatis怎么獲取最新插入數(shù)據(jù)的id”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

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

AI