myBatis使用@GeneratedValue(generator?=?“...“,?strategy?=?...)注解
一. @GeneratedValue注解id生成策略
使用范圍:方法和屬性
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface GeneratedValue {
/**
* (Optional) The primary key generation strategy
* that the persistence provider must use to
* generate the annotated entity primary key.
*/
GenerationType strategy() default AUTO;
/**
* (Optional) The name of the primary key generator
* to use as specified in the {@link SequenceGenerator}
* or {@link TableGenerator} annotation.
* <p> Defaults to the id generator supplied by persistence provider.
*/
String generator() default "";
}GenerationType:主鍵生成策略,有TABLE,SEQUENCE,IDENTITY,AUTO四種。generator:主鍵生成的來源,既由誰來執(zhí)行生成主鍵,從哪里獲取主鍵值。下面會(huì)講到mybatis可以配置的值。
二. GenerationType 定義主鍵策略的枚舉
/**
* Defines the types of primary key generation.
*
* @since Java Persistence 1.0
*/
public enum GenerationType {
/**
* Indicates that the persistence provider must assign
* primary keys for the entity using an underlying
* database table to ensure uniqueness.
*/
TABLE,
/**
* Indicates that the persistence provider must assign
* primary keys for the entity using database sequence column.
*/
SEQUENCE,
/**
* Indicates that the persistence provider must assign
* primary keys for the entity using database identity column.
*/
IDENTITY,
/**
* Indicates that the persistence provider should pick an
* appropriate strategy for the particular database. The
* <code>AUTO</code> generation strategy may expect a database
* resource to exist, or it may attempt to create one. A vendor
* may provide documentation on how to create such resources
* in the event that it does not support schema generation
* or cannot create the schema resource at runtime.
*/
AUTO
}1.GenerationType.TABLE
使用一個(gè)特定的數(shù)據(jù)庫表格來保存主鍵,持久化引擎通過關(guān)系數(shù)據(jù)庫的一張?zhí)囟ǖ谋砀駚砩芍麈I,這種策略的好處就是不依賴于外部環(huán)境和數(shù)據(jù)庫的具體實(shí)現(xiàn),在不同數(shù)據(jù)庫間可以很容易的進(jìn)行移植,但由于其不能充分利用數(shù)據(jù)庫的特性,所以不會(huì)優(yōu)先使用。
該策略一般與另外一個(gè)注解一起使用@TableGenerator,@TableGenerator注解指定了生成主鍵的表(可以在實(shí)體類上指定也可以在主鍵字段或?qū)傩陨现付?,然后JPA將會(huì)根據(jù)注解內(nèi)容自動(dòng)生成一張表作為序列表(或使用現(xiàn)有的序列表)。
如果不指定序列表,則會(huì)生成一張默認(rèn)的序列表,表中的列名也是自動(dòng)生成,數(shù)據(jù)庫上會(huì)生成一張名為sequence的表(SEQ_NAME,SEQ_COUNT)。
序列表一般只包含兩個(gè)字段:第一個(gè)字段是該生成策略的名稱,第二個(gè)字段是該關(guān)系表的最大序號,它會(huì)隨著數(shù)據(jù)的插入逐漸累加。
類似于
@Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "roleSeq") @TableGenerator(name = "roleSeq", allocationSize = 1, table = "seq_table", pkColumnName = "seq_id", valueColumnName = "seq_count") private Integer id;
在以上例子中,roleSeq唯一的標(biāo)識了該生成器,在@GeneratedValue注解中的generator屬性可以根據(jù)此標(biāo)識來聲明主鍵生成器。
2.GenerationType.SEQUENCE
在某些數(shù)據(jù)庫中,不支持主鍵自增長,比如Oracle,其提供了一種叫做"序列(sequence)"的機(jī)制生成主鍵。
此時(shí),GenerationType.SEQUENCE就可以作為主鍵生成策略。
該策略的不足之處正好與TABLE相反,由于只有部分?jǐn)?shù)據(jù)庫(Oracle,PostgreSQL,DB2)支持序列對象,所以該策略一般不應(yīng)用于其他數(shù)據(jù)庫。
類似的,該策略一般與另外一個(gè)注解一起使用@SequenceGenerator,@SequenceGenerator注解指定了生成主鍵的序列.然后JPA會(huì)根據(jù)注解內(nèi)容創(chuàng)建一個(gè)序列(或使用一個(gè)現(xiàn)有的序列)。
如果不指定序列,則會(huì)自動(dòng)生成一個(gè)序列SEQ_GEN_SEQUENCE。
類似于
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "menuSeq") @SequenceGenerator(name = "menuSeq", initialValue = 1, allocationSize = 1, sequenceName = "MENU_SEQUENCE") private Integer id;
同樣,在以上例子中,menuSeq唯一的標(biāo)識了該生成器,@SequenceGenerator可以理解為將數(shù)據(jù)庫中存在的序列進(jìn)行了一個(gè)映射,在@GeneratedValue注解中的generator屬性可以根據(jù)此標(biāo)識來聲明主鍵生成器。
3.GenerationType.IDENTITY
此種主鍵生成策略就是通常所說的主鍵自增長,數(shù)據(jù)庫在插入數(shù)據(jù)時(shí),會(huì)自動(dòng)給主鍵賦值,比如MYSQL可以在創(chuàng)建表時(shí)聲明"auto_increment" 來指定主鍵自增長。
該策略在大部分?jǐn)?shù)據(jù)庫中都提供了支持(指定方法或關(guān)鍵字可能不同),但還是有少數(shù)數(shù)據(jù)庫不支持,所以可移植性略差。
使用自增長主鍵生成策略是只需要聲明strategy = GenerationType.IDENTITY即可。
類似于
@Id @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "mysql") private Integer id;
需要注意的是,同一張表中自增列最多只能有一列。
4.GenerationType.AUTO
把主鍵生成策略交給持久化引擎(persistence engine),持久化引擎會(huì)根據(jù)數(shù)據(jù)庫在以上三種主鍵生成策略中選擇其中一種。
此種主鍵生成策略比較常用,由于JPA默認(rèn)的生成策略就是GenerationType.AUTO,所以使用此種策略時(shí)。
可以顯式的指定@GeneratedValue(strategy = GenerationType.AUTO)也可以直接@GeneratedValue
類似于
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
或
@GeneratedValue
private Integer id;三. myBatis 對@GeneratedValue的解析實(shí)現(xiàn)
// 包名
package tk.mybatis.mapper.mapperhelper;
//主鍵策略 - Oracle序列,MySql自動(dòng)增長,UUID
// Oracle序列生成注解
if (field.isAnnotationPresent(SequenceGenerator.class)) {
SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);
if (sequenceGenerator.sequenceName().equals("")) {
throw new RuntimeException(entityTable.getEntityClass() + "字段" + field.getName() + "的注解@SequenceGenerator未指定sequenceName!");
}
entityColumn.setSequenceName(sequenceGenerator.sequenceName());
//MySql自動(dòng)增長,UUID
} else if (field.isAnnotationPresent(GeneratedValue.class)) {
GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);
// 首先 通過generator 類型判斷主鍵生成類型
if (generatedValue.generator().equals("UUID")) {
entityColumn.setUuid(true);
} else if (generatedValue.generator().equals("JDBC")) {
entityColumn.setIdentity(true);
entityColumn.setGenerator("JDBC");
entityTable.setKeyProperties(entityColumn.getProperty());
entityTable.setKeyColumns(entityColumn.getColumn());
} else {
//允許通過generator來設(shè)置獲取id的sql,例如mysql=CALL IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY()
//允許通過攔截器參數(shù)設(shè)置公共的generator
// generator 不是UUID 和 JDBC時(shí) 判斷 strategy ;如果類型不是 GenerationType.IDENTITY 則會(huì)拋出異常
if (generatedValue.strategy() == GenerationType.IDENTITY) {
//mysql的自動(dòng)增長
entityColumn.setIdentity(true);
if (!generatedValue.generator().equals("")) {
String generator = null;
// 獲取generator 主鍵生成的來源
IdentityDialect identityDialect = IdentityDialect.getDatabaseDialect(generatedValue.generator());
if (identityDialect != null) {
generator = identityDialect.getIdentityRetrievalStatement();
} else {
generator = generatedValue.generator();
}
entityColumn.setGenerator(generator);
}
} else {
throw new RuntimeException(field.getName()
+ " - 該字段@GeneratedValue配置只允許以下幾種形式:" +
"\n1.全部數(shù)據(jù)庫通用的@GeneratedValue(generator=\"UUID\")" +
"\n2.useGeneratedKeys的@GeneratedValue(generator=\\\"JDBC\\\") " +
"\n3.類似mysql數(shù)據(jù)庫的@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"Mysql\"])");
}
}
}
entityTable.getEntityClassColumns().add(entityColumn);
if (entityColumn.isId()) {
entityTable.getEntityClassPKColumns().add(entityColumn);
}由上面的mybatis對@GeneratedValue注解的解析可知 :
1.Mybatis先解析注解@GeneratedValue 中的generator,
2.如果generator的值不是UUID 和 JDBC時(shí),再判斷 strategy ,
3.如果類型不是 GenerationType.IDENTITY 則會(huì)拋出異常,
4.因此strategy在使用mybatis框架時(shí),值必須是GenerationType.IDENTITY,
5.而generator的取值可以在下面的枚舉中看到,且不區(qū)分大小寫。
package tk.mybatis.mapper.code;
public enum IdentityDialect {
DB2("VALUES IDENTITY_VAL_LOCAL()"),
MYSQL("SELECT LAST_INSERT_ID()"),
SQLSERVER("SELECT SCOPE_IDENTITY()"),
CLOUDSCAPE("VALUES IDENTITY_VAL_LOCAL()"),
DERBY("VALUES IDENTITY_VAL_LOCAL()"),
HSQLDB("CALL IDENTITY()"),
SYBASE("SELECT @@IDENTITY"),
DB2_MF("SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1"),
INFORMIX("select dbinfo('sqlca.sqlerrd1') from systables where tabid=1");
private String identityRetrievalStatement;
private IdentityDialect(String identityRetrievalStatement) {
this.identityRetrievalStatement = identityRetrievalStatement;
}
public static IdentityDialect getDatabaseDialect(String database) {
IdentityDialect returnValue = null;
if ("DB2".equalsIgnoreCase(database)) {
returnValue = DB2;
} else if ("MySQL".equalsIgnoreCase(database)) {
returnValue = MYSQL;
} else if ("SqlServer".equalsIgnoreCase(database)) {
returnValue = SQLSERVER;
} else if ("Cloudscape".equalsIgnoreCase(database)) {
returnValue = CLOUDSCAPE;
} else if ("Derby".equalsIgnoreCase(database)) {
returnValue = DERBY;
} else if ("HSQLDB".equalsIgnoreCase(database)) {
returnValue = HSQLDB;
} else if ("SYBASE".equalsIgnoreCase(database)) {
returnValue = SYBASE;
} else if ("DB2_MF".equalsIgnoreCase(database)) {
returnValue = DB2_MF;
} else if ("Informix".equalsIgnoreCase(database)) {
returnValue = INFORMIX;
}
return returnValue;
}
public String getIdentityRetrievalStatement() {
return identityRetrievalStatement;
}
}因此,項(xiàng)目集成mybatis 使用mysql數(shù)據(jù)庫的主鍵配置為:

strategy:必須為 GenerationType.IDENTITY;generator: mysql大寫忽略。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于MD5算法原理與常用實(shí)現(xiàn)方式
這篇文章主要介紹了關(guān)于MD5算法原理與常用實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
RestTemplate發(fā)送請求時(shí)Cookie的影響及注意事項(xiàng)說明
這篇文章主要介紹了RestTemplate發(fā)送請求時(shí)Cookie的影響及注意事項(xiàng)說明,具有很好的參考價(jià)值,希望對大家有所幫助。2023-07-07
SpringBoot中整合Shiro實(shí)現(xiàn)權(quán)限管理的示例代碼
這篇文章主要介紹了SpringBoot中整合Shiro實(shí)現(xiàn)權(quán)限管理的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
SpringBoot 分布式驗(yàn)證碼登錄方案示例詳解
為了防止驗(yàn)證系統(tǒng)被暴力破解,很多系統(tǒng)都增加了驗(yàn)證碼效驗(yàn),比較常見的就是圖片二維碼,業(yè)內(nèi)比較安全的是短信驗(yàn)證碼,當(dāng)然還有一些拼圖驗(yàn)證碼,加入人工智能的二維碼等等,我們今天的主題就是前后端分離的圖片二維碼登錄方案,感興趣的朋友一起看看吧2023-10-10
SpringBoot整合日志功能(slf4j+logback)詳解(最新推薦)
Spring使用commons-logging作為內(nèi)部日志,但底層日志實(shí)現(xiàn)是開放的,可對接其他日志框架,這篇文章主要介紹了SpringBoot整合日志功能(slf4j+logback)詳解,需要的朋友可以參考下2024-08-08
Java中的Static class詳解及實(shí)例代碼
這篇文章主要介紹了 Java中的Static class詳解及實(shí)例代碼的相關(guān)資料,在Java中我們可以有靜態(tài)實(shí)例變量、靜態(tài)方法、靜態(tài)塊。類也可以是靜態(tài)的,需要的朋友可以參考下2017-03-03

