A, JPA generator strategy adopted by General annotation to hibernate entity mapping, annotation based on the logo to hibernate primary key @ Id,
The generation of rules set by the @ GeneratedValue. Here @ id and @ GeneratedValue are standard JPA usage,
JPA offers four standard usage, @ GeneratedValue from the source code is evident.
Java code
- @ Target ((METHOD, FIELD))
- @ Retention (RUNTIME)
- public @ interface GeneratedValue (
- GenerationType strategy () default AUTO;
- String generator () default "";
- )
@Target({METHOD,FIELD})
@Retention(RUNTIME)
public @interface GeneratedValue{
GenerationType strategy() default AUTO;
String generator() default "";
} Which GenerationType:
Java code
- public enum GenerationType (
- TABLE,
- SEQUENCE,
- IDENTITY,
- AUTO
- )
public enum GenerationType{
TABLE,
SEQUENCE,
IDENTITY,
AUTO
} JPA provides for the use of four standard TABLE, SEQUENCE, IDENTITY, AUTO.
TABLE: the use of a specific database table to store the primary key.
SEQUENCE: the sequence in accordance with the underlying database to generate the primary key, on the condition that supports the sequence database.
IDENTITY: primary key automatically generated by the database (mainly automatic growth)
AUTO: the primary key from the control.
1, TABLE
Java code
- @ Id
- @ GeneratedValue (strategy = GenerationType.TABLE, generator = "payablemoney_gen")
- @ TableGenerator (name = "pk_gen",
- table = "tb_generator",
- pkColumnName = "gen_name",
- valueColumnName = "gen_value",
- pkColumnValue = "PAYABLEMOENY_PK",
- allocationSize = 1
- )
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator="payablemoney_gen")
@TableGenerator(name = "pk_gen",
table="tb_generator",
pkColumnName="gen_name",
valueColumnName="gen_value",
pkColumnValue="PAYABLEMOENY_PK",
allocationSize=1
) Application form here tb_generator, defined as
Sql code
- CREATE TABLE tb_generator (
- id NUMBER NOT NULL,
- gen_name VARCHAR2 (255) NOT NULL,
- gen_value NUMBER NOT NULL,
- PRIMARY KEY (id)
- )
CREATE TABLE tb_generator ( id NUMBER NOT NULL, gen_name VARCHAR2(255) NOT NULL, gen_value NUMBER NOT NULL, PRIMARY KEY(id) )
Insert a record for the use of primary key generation,
Sql code
- INSERT INTO tb_generator (id, gen_name, gen_value) VALUES (1, PAYABLEMOENY_PK ', 1);
INSERT INTO tb_generator(id, gen_name, gen_value) VALUES (1,PAYABLEMOENY_PK', 1);
Generated in the primary key, the record value of this value, increasing by allocationSize.
@ TableGenerator definition:
Java code
- @ Target ((TYPE, METHOD, FIELD))
- @ Retention (RUNTIME)
- public @ interface TableGenerator (
- String name ();
- String table () default "";
- String catalog () default "";
- String schema () default "";
- String pkColumnName () default "";
- String valueColumnName () default "";
- String pkColumnValue () default "";
- int initialValue () default 0;
- int allocationSize () default 50;
- UniqueConstraint [] uniqueConstraints () default ();
- )
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface TableGenerator {
String name();
String table() default "";
String catalog() default "";
String schema() default "";
String pkColumnName() default "";
String valueColumnName() default "";
String pkColumnValue() default "";
int initialValue() default 0;
int allocationSize() default 50;
UniqueConstraint[] uniqueConstraints() default {};
} One attribute Description:
name attribute that to generate the primary key of the table the name of the strategy, which was quoted in the set @ GeneratedValue the "generator" values.
table table attributes that generate lasting strategy of the table name, for example, here is a table used in the database "tb_generator".
schema and catalog attributes specify the directory name where the table or database name.
pkColumnName the value of property in the persistent table, the primary key generation strategy that corresponds to the name of key. For example, in "tb_generator" will "gen_name" as the primary key of the key
valueColumnName the value of property in the persistent table, the primary key value generated by the current, its value will be cumulative with each creation. For example, in "tb_generator" will "gen_value" as a primary key value
pkColumnValue the value of property in the persistent table, the strategy generated by the corresponding primary key. For example, in "tb_generator" table will be "gen_name" value "CUSTOMER_PK".
initialValue acquaintance that the primary key value, the default is 0.
allocationSize that each increase in the size of primary key values, for example, set to 1, then create a new record each time automatic plus 1, the default is 50.
@ Table and UniqueConstraint the use of similar tags.
2, SEQUENCE
Java code
- @ Id
- @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "payablemoney_seq")
- @ SequenceGenerator (name = "payablemoney_seq", sequenceName = "seq_payment")
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="payablemoney_seq") @SequenceGenerator(name="payablemoney_seq", sequenceName="seq_payment")
@ SequenceGenerator the definition of
Java code
- @ Target ((TYPE, METHOD, FIELD))
- @ Retention (RUNTIME)
- public @ interface SequenceGenerator (
- String name ();
- String sequenceName () default "";
- int initialValue () default 0;
- int allocationSize () default 50;
- )
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface SequenceGenerator {
String name();
String sequenceName() default "";
int initialValue() default 0;
int allocationSize() default 50;
} name attribute that to generate the primary key of the table the name of the strategy, which was quoted in the set @ GeneratedValue the "generator" values.
sequenceName property strategy that is used to generate the name of the database sequences.
initialValue acquaintance that the primary key value, the default is 0.
allocationSize that each increase in the size of primary key values, for example, set to 1, then create a new record each time automatic plus 1, the default is 50.
3, IDENTITY
Java code
- @ Id
- @ GeneratedValue (strategy = GenerationType.IDENTITY)
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
4, AUTO
Java code
- @ Id
- @ GeneratedValue (strategy = GenerationType.AUTO)
@Id @GeneratedValue(strategy = GenerationType.AUTO)
Primary key in the designated time, If you do not specify the primary key generation strategy, default is AUTO.
Java code
- @ Id
@Id
With the following definition is the same.
Java code
- @ Id
- @ GeneratedValue (strategy = GenerationType.AUTO)
@Id @GeneratedValue(strategy = GenerationType.AUTO)
Second, hibernate primary key generator strategy
provides a wide range of hibernate primary key generation strategy is somewhat similar to JPA, some specific to hibernate:
native: the use of the oracle way Sequence for MySQL and SQL Server using identity (self-formation mechanism by the primary key), native to the primary key is the generation of work completed by the database, hibernate regardless of (very common).
uuid: The uuid using 128-bit algorithm to generate the primary key, uuid is encoded as a 32-bit 16-digit hexadecimal string. Large space (string type).
hilo: used to generate hilo strategy to create an extra database table, the default table name hibernate_unique_key, the default fields for the integer type, the name is next_hi (use less).
assigned: insert data in the primary key from the time of the procedure (very common), this is not specified <generator> element generated at the time of the default strategy. Equivalent to JPA in AUTO.
identity: the use of SQL Server and MySQL by the self-field, this method can not be put Oracle in, Oracle does not support self-growing field, it is necessary to set the sequence (MySQL and SQL Server in a very commonly used).
Equivalent to JPA in INDENTITY.
select: the use of flip-flop to generate the primary key (the main database for the early primary key generation mechanism, the use of).
sequence: call the bottom of the sequence database to generate the primary key, it is necessary to set the sequence name, otherwise can not find hibernate.
seqhilo: through the hilo algorithm, but the primary key of the history stored in the Sequence for Sequence database support, such as Oracle (using less)
increment: Insert data will hibernate when the primary key to add an auto-incremented primary key, but a hibernate on the maintenance of a counter example, so when running multiple instances can not use this method.
foreign: the use of another object associated with the primary key. <one-to-one> Usually used together.
guid: the guid database algorithm underlying mechanism, the corresponding MYSQL the uuid () function, SQL Server's newid () function, ORACLE's rawtohex (sys_guid ()) function and so on.
uuid.hex: see uuid, proposed to replace uuid.
sequence-identity: sequence expansion strategy, the strategy used to obtain immediate access sequence value, the need for more than JDBC3.0 and JDK4 (including 1.4) version
hibernate generator provides a wide range of options, Annotation-based @ GenericGenerator adopted to achieve.
hibernate primary key for each interface to generate strategies for the realization of org.hibernate.id.IdentifierGenerator category, if we are to achieve self-definition of the primary key generation strategy must also be the realization of this interface.
Java code
- public interface IdentifierGenerator (
- / **
- * The configuration parameter holding the entity name
- * /
- public static final String ENTITY_NAME = "entity_name";
- / **
- * Generate a new identifier.
- * @ Param session
- * @ Param object the entity or toplevel collection for which the id is being generated
- *
- * @ Return a new identifier
- * @ Throws HibernateException
- * /
- public Serializable generate (SessionImplementor session, Object object)
- throws HibernateException;
- )
public interface IdentifierGenerator {
/**
* The configuration parameter holding the entity name
*/
public static final String ENTITY_NAME = "entity_name";
/**
* Generate a new identifier.
* @param session
* @param object the entity or toplevel collection for which the id is being generated
*
* @return a new identifier
* @throws HibernateException
*/
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException;
} C, @ GenericGenerator
Since the definition of primary key generation strategy by @ GenericGenerator achieve.
hibernate in JPA based on the expansion can be used like the way hibernate introduced to generate unique primary key strategy is to add @ GenericGenerator through.
For example, JPA standard usage
Java code
- @ Id
- @ GeneratedValue (GenerationType.AUTO)
@Id @GeneratedValue(GenerationType.AUTO)
Hibernate can be used on the specific use to achieve the following
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "assigned")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "assigned")
@ GenericGenerator definition:
Java code
- @ Target ((PACKAGE, TYPE, METHOD, FIELD))
- @ Retention (RUNTIME)
- public @ interface GenericGenerator (
- / **
- * Unique generator name
- * /
- String name ();
- / **
- * Generator strategy either a predefined Hibernate
- * Strategy or a fully qualified class name.
- * /
- String strategy ();
- / **
- * Optional generator parameters
- * /
- Parameter [] parameters () default ();
- )
@Target({PACKAGE, TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface GenericGenerator {
/**
* unique generator name
*/
String name();
/**
* Generator strategy either a predefined Hibernate
* strategy or a fully qualified class name.
*/
String strategy();
/**
* Optional generator parameters
*/
Parameter[] parameters() default {};
} name attribute specifies the name generator.
strategy attributes specify class name generator.
parameters to be specified strategy by using specific generator parameters.
For those hibernate primary key generation strategies and their specific relationship between the generator, in org.hibernate.id.IdentifierGeneratorFactory specified,
Java code
- static (
- GENERATORS.put ( "uuid", UUIDHexGenerator. Class);
- GENERATORS.put ( "hilo", TableHiLoGenerator. Class);
- GENERATORS.put ( "assigned", Assigned. Class);
- GENERATORS.put ( "identity", IdentityGenerator. Class);
- GENERATORS.put ( "select", SelectGenerator. Class);
- GENERATORS.put ( "sequence", SequenceGenerator. Class);
- GENERATORS.put ( "seqhilo", SequenceHiLoGenerator. Class);
- GENERATORS.put ( "increment", IncrementGenerator. Class);
- GENERATORS.put ( "foreign", ForeignGenerator. Class);
- GENERATORS.put ( "guid", GUIDGenerator. Class);
- GENERATORS.put ( "uuid.hex", UUIDHexGenerator. Class); / / uuid.hex is deprecated
- GENERATORS.put ( "sequence-identity", SequenceIdentityGenerator. Class);
- )
static {
GENERATORS.put("uuid", UUIDHexGenerator.class);
GENERATORS.put("hilo", TableHiLoGenerator.class);
GENERATORS.put("assigned", Assigned.class);
GENERATORS.put("identity", IdentityGenerator.class);
GENERATORS.put("select", SelectGenerator.class);
GENERATORS.put("sequence", SequenceGenerator.class);
GENERATORS.put("seqhilo", SequenceHiLoGenerator.class);
GENERATORS.put("increment", IncrementGenerator.class);
GENERATORS.put("foreign", ForeignGenerator.class);
GENERATORS.put("guid", GUIDGenerator.class);
GENERATORS.put("uuid.hex", UUIDHexGenerator.class); //uuid.hex is deprecated
GENERATORS.put("sequence-identity", SequenceIdentityGenerator.class);
} 12 kinds of the above strategies, together with the native, hibernate a total of 13 kinds of support to generate the default strategy.
1, native
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "native")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "native")
2, uuid
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "uuid")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
3, hilo
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "hilo")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "hilo")
4, assigned
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "assigned")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "assigned")
5, identity
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "identity")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "identity")
6, select
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "select", strategy = "select",
- parameters = (@ Parameter (name = "key", value = "idstoerung")))
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name="select", strategy="select",
parameters = { @Parameter(name = "key", value = "idstoerung") })
7, sequence
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "sequence",
- parameters = (@ Parameter (name = "sequence", value = "seq_payablemoney")))
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "sequence",
parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })
8, seqhilo
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "seqhilo",
- parameters = (@ Parameter (name = "max_lo", value = "5")))
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "seqhilo",
parameters = { @Parameter(name = "max_lo", value = "5") })
9, increment
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "increment")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "increment")
10, foreign
Java code
- @ GeneratedValue (generator = "idGenerator")
- @ GenericGenerator (name = "idGenerator", strategy = "foreign",
- parameters = (@ Parameter (name = "property", value = "employee")))
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "foreign",
parameters = { @Parameter(name = "property", value = "employee") }) Note: Direct use of @ PrimaryKeyJoinColumn error (?)
Java code
- @ OneToOne (cascade = CascadeType.ALL)
- @ PrimaryKeyJoinColumn
@OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn
For example,
Java code
- @ Entity
- public class Employee (
- @ Id Integer id;
- @ OneToOne @ PrimaryKeyJoinColumn
- EmployeeInfo info;
- ...
- )
@Entity
public class Employee {
@Id Integer id;
@OneToOne @PrimaryKeyJoinColumn
EmployeeInfo info;
...
} Should
Java code
- @ Entity
- public class Employee (
- @ Id
- @ GeneratedValue (generator = "idGenerator")
- @ GenericGenerator (name = "idGenerator", strategy = "foreign",
- parameters = (@ Parameter (name = "property", value = "info")))
- Integer id;
- @ OneToOne
- EmployeeInfo info;
- ...
- )
@Entity
public class Employee {
@Id
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "foreign",
parameters = { @Parameter(name = "property", value = "info") })
Integer id;
@OneToOne
EmployeeInfo info;
...
} 11, guid
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "guid")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "guid")
12, uuid.hex
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "uuid.hex")
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid.hex")
13, sequence-identity
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "sequence-identity",
- parameters = (@ Parameter (name = "sequence", value = "seq_payablemoney")))
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "sequence-identity",
parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") }) Fourth, through a custom @ GenericGenerator primary key generation strategy if the actual application, the primary key strategies for the procedures specified by the procedures specified on the primary key (assigned), not specified in the check from the sequence.
Obviously the strategy discussed above are not met, had no choice but to own the expansion, integration and sequence of two strategies assigned.
Java code
- public class AssignedSequenceGenerator extends SequenceGenerator implements
- PersistentIdentifierGenerator, Configurable (
- private String entityName;
- public void configure (Type type, Properties params, Dialect dialect) throws MappingException (
- entityName = params.getProperty (ENTITY_NAME);
- if (entityName == null) (
- throw new MappingException ( "no entity name");
- )
- super. configure (type, params, dialect);
- )
- public Serializable generate (SessionImplementor session, Object obj)
- throws HibernateException (
- Serializable id = session.getEntityPersister (entityName, obj)
- . getIdentifier (obj, session.getEntityMode ());
- if (id == null) (
- id = super. generate (session, obj);
- )
- return id;
- )
- )
public class AssignedSequenceGenerator extends SequenceGenerator implements
PersistentIdentifierGenerator, Configurable {
private String entityName;
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
entityName = params.getProperty(ENTITY_NAME);
if (entityName==null) {
throw new MappingException("no entity name");
}
super.configure(type, params, dialect);
}
public Serializable generate(SessionImplementor session, Object obj)
throws HibernateException {
Serializable id = session.getEntityPersister( entityName, obj )
.getIdentifier( obj, session.getEntityMode() );
if (id==null) {
id = super.generate(session, obj);
}
return id;
}
} Practical application, the definition of the same sequence.
Java code
- @ GeneratedValue (generator = "paymentableGenerator")
- @ GenericGenerator (name = "paymentableGenerator", strategy = "AssignedSequenceGenerator",
- parameters = (@ Parameter (name = "sequence", value = "seq_payablemoney")))
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "AssignedSequenceGenerator",
parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })
It is worth noting that the definition of such a strategy, just opened up a Pandora's Box, is not controllable. Under normal circumstances, is not recommended to do so.







