Mybatis使用useGeneratedKeys獲取自增主鍵
一、useGeneratedKeys 是什么 ?
關(guān)于useGeneratedKeys,官方的說法是,這個(gè)參數(shù)的作用是:"允許 JDBC 支持自動(dòng)生成主鍵,需要驅(qū)動(dòng)兼容",如何理解這句話的含義?
其原意是。對于支持自動(dòng)生成記錄主鍵的數(shù)據(jù)庫,如 MySQL 和 SQL Server,此時(shí)將 useGeneratedKeys 參數(shù)的值設(shè)置為 true,則進(jìn)行 INSERT 操作后,數(shù)據(jù)庫自動(dòng)生成的主鍵會(huì)填充到 Java 實(shí)體屬性中,我們可以從 Java 實(shí)體屬性中獲得數(shù)據(jù)庫自動(dòng)生成的主鍵 ID。
二、如何使用?
配置useGeneratedKeys,可以通過以下方式實(shí)現(xiàn):
- 配置全局配置文件
- 在 xml 映射器中配置 useGeneratedKeys 參數(shù)
- 在接口映射器中設(shè)置 useGeneratedKeys 參數(shù)
2.1 在 mybatis 的全局配置文件中配置
application.yml 配置文件
通過 configLocation 指定 mybatis 的配置文件 mybatis-config.xml
# MyBatis configuration
mybatis:
# Search for the specified package alias
typeAliasesPackage: com.ruoyi.**.domain
# Configure mapper scan to find all mapper.xml mapping files
mapperLocations: classpath*:mapper/**/*Mapper.xml
# Load the global configuration file
configLocation: classpath:mybatis/mybatis-config.xml
mybatis-config.xml
通過<setting name="useGeneratedKeys" value="true" />激活useGeneratedKeys.
<?xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" /> <!-- global mapper enables caching -->
<setting name="useGeneratedKeys" value="true" /> <!-- Allow JDBC to support automatic generation of primary keys -->
<setting name="defaultExecutorType" value="REUSE" /> <!-- configure the default executor -->
<setting name="logImpl" value="SLF4J" /> <!-- Specify the specific implementation of the log used by MyBatis -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> <!– CamelCase naming–>-->
</settings>
</configuration>
注意:在settings元素中設(shè)置的全局 useGeneratedKeys 參數(shù)對 xml 后綴的 mapper 無效。如果你想在 xml 后綴的 mapper 中添加記錄后返回主鍵 ID,你必須在 xml 后綴的 mapper 中明確設(shè)置useGeneratedKeys參數(shù)的值為 true。
2.2 在 xml mapper 中配置 useGeneratedKeys 參數(shù)。
Mapper.xml
<insert id="addBigdataGroup" parameterType="BigdataGroup" useGeneratedKeys="true" keyProperty="groupId" keyColumn="group_id">
insert into bigdata_group (
group_id, group_name, comment, business_line, create_by, remark, create_time)
values(#{groupId}, #{groupName}, #{comment}, #{businessLine}, #{createBy}, #{remark}, sysdate() );
</insert>
parameterType 傳入?yún)?shù)類型
keyProperty JAVA 對象中的屬性名稱
keyColumn 數(shù)據(jù)庫字段名稱

keyProperty與keyColumn的關(guān)系圖示(來自網(wǎng)絡(luò)).png
再次說明:在 xml mapper 中配置的 useGeneratedKeys 參數(shù)只影響 xml mapper,設(shè)置元素中設(shè)置的全局 useGeneratedKeys 參數(shù)值對 xml mapper 沒有影響。
2.3 在 interface mapper 中設(shè)置 useGeneratedKeys 參數(shù)
設(shè)置 useGeneratedKeys 為 true,返回由數(shù)據(jù)庫自動(dòng)生成的記錄主鍵 id。
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into test(name,descr,url,create_time,update_time) values(#{name},#{descr},#{url},now(),now())")
Integer insertOneTest(Test test);
注意:在 interface mapper 中設(shè)置的 useGeneratedKeys參數(shù)將覆蓋 mybatis 配置文件中 setting 元素內(nèi)所配置的useGeneratedKeys的值。
另外筆者的實(shí)踐中,keyProperty = "id"并未生效,需要設(shè)置為keyProperty = "test.id";即參數(shù)的名稱 + . + 主鍵屬性名。 讀者老師需結(jié)合自己的環(huán)境試一試。
三、遇到的問題
在配置了獲得主鍵 ID 后,但返回的結(jié)果并沒有像預(yù)期的那樣返回新插入數(shù)據(jù)庫行的主鍵的真實(shí)數(shù)據(jù)。但返回的居然1。
代碼示例如下:
- Mybatis 側(cè)
import java.util.List;
public interface BigdataMapper {
List<BigdataGroup> getBigdataGroup();
int addBigdataGroup(BigdataGroup bigdataGroup);
}
- service 側(cè)
public int addBigdataGroup(BigdataGroup bigdataGroup) {
bigdataGroup.setCreateBy(SecurityUtils.getUsername());
int update = bigdataMapper. addBigdataGroup(bigdataGroup);
log.info("update: {}", update);
return update;
}
- xml file側(cè)
<insert id="addBigdataGroup" parameterType="BigdataGroup" useGeneratedKeys="true" keyProperty="groupId" keyColumn="group_id">
insert into bigdata_group (
group_id, group_name, comment, business_line, create_by, remark, create_time)
values(#{groupId}, #{groupName}, #{comment}, #{businessLine}, #{createBy}, #{remark}, sysdate() );
</insert>
- 打印結(jié)果
按理說,返回的結(jié)果應(yīng)該是插入后主鍵中的真實(shí)數(shù)據(jù),但返回結(jié)果是1。
注意:真實(shí)的 id 已經(jīng)被注入到參數(shù)傳遞對象的主鍵的相應(yīng)屬性中,方法的返回值實(shí)際表示的是插入的行數(shù),因?yàn)椴迦肓?1 條記錄,所以返回值是 1;如果要獲得新添加數(shù)據(jù)的自增ID,那么只需要讀取對象中對應(yīng)的自增ID屬性的值。
修改獲取主鍵值的方式:
public int addBigdataGroup(BigdataGroup bigdataGroup) {
bigdataGroup.setCreateBy(SecurityUtils.getUsername());
int update = bigdataMapper. addBigdataGroup(bigdataGroup);
log.info("update: {}", update);
// Add the following code
int group_id = bigdataGroup. getGroupId();
log.info("group_id: {}", group_id);
// stop here
return update;
}
結(jié)語
以上就是Mybatis使用useGeneratedKeys獲取自增主鍵的詳細(xì)內(nèi)容,更多關(guān)于Mybatis useGeneratedKeys自增主鍵的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Boot搭配MinIO和KKFileView實(shí)現(xiàn)文件存儲(chǔ)和在線預(yù)覽
在現(xiàn)代的Web應(yīng)用中,文件上傳和預(yù)覽是常見的需求場景,尤其是在內(nèi)容管理系統(tǒng)(CMS)或企業(yè)內(nèi)部應(yīng)用,本文介紹了如何使用SpringBoot、MinIO和KKFileView實(shí)現(xiàn)文件上傳和在線預(yù)覽功能,包括項(xiàng)目背景、技術(shù)選型、環(huán)境準(zhǔn)備、項(xiàng)目代碼實(shí)現(xiàn)和運(yùn)行測試等步驟2024-12-12
Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案
在筆者面試過程時(shí),經(jīng)常會(huì)被問到各種各樣的鎖,如樂觀鎖、讀寫鎖等等,非常繁多,下面這篇文章主要給大家介紹了關(guān)于Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
Maven多模塊之父子關(guān)系的創(chuàng)建
這篇文章主要介紹了Maven多模塊之父子關(guān)系的創(chuàng)建,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

