MyBatis insert語句返回主鍵和selectKey標簽方式
insert語句返回主鍵和selectKey標簽
往數(shù)據(jù)庫中插入一條記錄后,有時候我們需要這條記錄的主鍵,用于后續(xù)的操作。
如果在插入后再去查一次數(shù)據(jù)庫,顯然不夠優(yōu)雅和效率,MyBatis中已經(jīng)有了insert后返回主鍵的功能,下面就主要講幾種不同情況的具體做法。
1.主鍵自增的情況
對于MySQL和Sql Server這種支持主鍵自增的數(shù)據(jù)庫,可以設置useGeneratedKeys="true"和keyProperty。例如現(xiàn)在有一個表 tbl_employee,表有id,name,age,create_time四個字段,MyBatis映射文件中可以寫成如下:
<insert id="insertRecord" parameterType="com.lzumetal.mybatis.entity.Employee"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO tbl_employee(name, age, create_time)
VALUES(#{name}, #{age}, #{createTime})
</insert>
- useGeneratedKeys="true":使用自動生成的主鍵
- keyProperty:指定主鍵是(javaBean的)哪個屬性。
useGeneratedKeys:
(insert and update only) This tells MyBatis to use the JDBC getGeneratedKeys method to retrieve keys generated internally by the database (e.g.auto increment fields in RDBMS like MySQL or SQL Server). Default: false
keyProperty:
(insert and update only) Identifies a property into which MyBatis will set the key value returned by getGeneratedKeys , or by a selectKey child element of the insert statement. Default: unset .
Can be a comma separated list of property names if multiple generated columns are expected.
2.Oracle中用Sequence獲取主鍵
對于Oracle數(shù)據(jù)庫,當要用到自增字段時,需要用到Sequence,假設我們現(xiàn)在已經(jīng)創(chuàng)建了一個名字為SEQ_ADMIN的 Sequence,在MyBatis中的映射文件中可以結合selectKey標簽使用。
<insert id="insert" parameterType="com.lzumetal.mybatis.entity.Employee">
<selectKey keyProperty="id" resultType="long" order="BEFORE">
SELECT SEQ_ADMIN.NEXTVAL FROM DUAL
</selectKey>
INSERT INTO tbl_employee(id, name, age, create_time)
VALUES(#{id}, #{name}, #{age}, #{createTime})
</insert>
order="BEFORE"表示SELECT SEQ_ADMIN.NEXTVAL FROM DUAL在 INSERT 語句執(zhí)行之前先對id進行賦值。相反的,order還可以設置成AFTER,表示在INSERT語句執(zhí)行完后,再查詢一次slectKey標簽中的語句,并賦值到Javabean的keyProperty的那個屬性上。
源碼分析
從源碼上來分析,在BaseStatementHandler里面有生成generateKeys,主要是執(zhí)行:
protected void generateKeys(Object parameter) {
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
ErrorContext.instance().store();
keyGenerator.processBefore(executor, mappedStatement, null, parameter);
ErrorContext.instance().recall();
}
processBefore,表示執(zhí)行前處理,對應mapper里面的selectKey中的order="BEFORE"屬性,先執(zhí)行查詢key,并設置到參數(shù)對象中。
在各個聲明處理器中,update有代碼:
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator(); keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);
processAfter,表示執(zhí)行后處理,對應mapper里面的selectKey中的order="AFTER"屬性,表示執(zhí)行后,再查一遍key,設置到參數(shù)對象中。
MyBatis insert語句key的生成和返回
1.使用數(shù)據(jù)庫自帶的生成器
<insert id="insertOne" keyProperty="userId" useGeneratedKeys="true" >
insert into user (user_name) values(#{userName})
</insert>
mybatis會獲取數(shù)據(jù)庫自動生成的列,并把值賦值給傳入?yún)?shù)的userId屬性。
2.使用selectKey
<insert id="insertOne" >
insert into user (user_name) values(#{userName})
<selectKey order="AFTER" keyProperty="userId">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
插入語句執(zhí)行后selectKey語句,并把返回值塞進傳入?yún)?shù)的userId屬性。
<insert id="insertOne" >
insert into user (user_name) values(#{userName})
<selectKey order="BEFORE" keyProperty="userId">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
先執(zhí)行selectKey,并把返回值賦值給傳入?yún)?shù)的userId屬性,然后執(zhí)行insert語句。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- mybatis?selectKey賦值未生效的原因分析
- Mybatis3中方法返回生成的主鍵:XML,@SelectKey,@Options詳解
- mybatis?獲取更新(update)記錄的id之<selectKey>用法說明
- mybatis的selectKey作用詳解
- Mybatis?selectKey 如何返回新增用戶的id值
- MyBatis如何使用selectKey返回主鍵的值
- Mybatis插入時返回自增主鍵方式(selectKey和useGeneratedKeys)
- Mybatis @SelectKey用法解讀
- Mybatis示例之SelectKey的應用
- MyBatis中selectKey標簽及主鍵回填實現(xiàn)
相關文章
Idea 解決 Could not autowire. No beans of ''xxxx'' type found
這篇文章主要介紹了Idea 解決 Could not autowire. No beans of 'xxxx' type found 的錯誤提示,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
spring boot使用自定義的線程池執(zhí)行Async任務
這篇文章主要介紹了spring boot使用自定義的線程池執(zhí)行Async任務的相關資料,需要的朋友可以參考下2018-02-02
Java中HashMap和TreeMap的區(qū)別深入理解
首先介紹一下什么是Map。在數(shù)組中我們是通過數(shù)組下標來對其內(nèi)容索引的,而在Map中我們通過對象來對對象進行索引,用來索引的對象叫做key,其對應的對象叫做value2012-12-12
詳解Spring Kafka中關于Kafka的配置參數(shù)
這篇文章主要介紹了詳解Spring Kafka中關于Kafka的配置參數(shù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

