當前位置:
首頁 > 知識 > mybatis和Mysql返回插入的主鍵ID

mybatis和Mysql返回插入的主鍵ID

需求:使用MyBatis往MySQL資料庫中插入一條記錄後,需要返回該條記錄的主鍵值

自增主鍵返回

思路:

通過mysql函數獲取到剛插入記錄的自增主鍵:LAST_INSERT_ID()

執行過程:

執行insert提交之前自動生成一個自增主鍵,在insert之後調用此函數。

函數解釋:

keyProperty:將查詢到主鍵值設置到parameterType指定的對象的哪個屬性

order:SELECT LAST_INSERT_ID()執行順序,相對於insert語句來說它的執行順序

resultType:指定SELECT LAST_INSERT_ID()的結果類型

<!-- 添加用戶
parameterType:指定輸入 參數類型是pojo(包括 用戶信息)
#{}中指定pojo的屬性名,接收到pojo對象的屬性值,mybatis通過OGNL獲取對象的屬性值
-->
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
<!--
</insert>
1
2
3
4
5
6
7
8
9
10
11
12

非自增主鍵返回

思路:

使用mysql的uuid()函數生成主鍵,需要修改表中id欄位類型為string,長度設置成35位。

執行過程:

首先通過uuid()得到主鍵,將主鍵設置到user對象的id屬性中,其次在insert執行時,從user對象中取出id屬性值

執行uuid()語句順序相對於insert語句之前執行。

<!-- 添加用戶
parameterType:指定輸入 參數類型是pojo(包括 用戶信息)
#{}中指定pojo的屬性名,接收到pojo對象的屬性值,mybatis通過OGNL獲取對象的屬性值
-->
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<!--
將插入數據的主鍵返回,返回到user對象中
使用mysql的uuid()生成主鍵
執行過程:
首先通過uuid()得到主鍵,將主鍵設置到user對象的id屬性中
其次在insert執行時,從user對象中取出id屬性值
-->
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
SELECT uuid()
</selectKey>
insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})
</insert>

mybatis和Mysql返回插入的主鍵ID

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

操作系統開發什麼是內核?
DeepLearning-Ng編程中遇到的一些問題

TAG:程序員小新人學習 |