Hibernate provides a primary key generation strategy that allows us to set the keyword in the mapping XML file of the entity class to tell hibernate how we want to generate the primary key, and Hibernate will then complete the primary key control of the database according to the settings.
The principle, characteristics and application of the primary key generation strategy commonly used in Hibernate :
1, Increment
The surrogate primary key used to generate a unique identity for the long,short or int type. It can only be used if no other process is inserting data into the same table. Do not use under the cluster. The primary key self-increment is maintained by hibernate, independent of the underlying database, but not suitable for 2 or more hibernate processes.
A new primary key is generated in the form of automatic sequential growth of the primary key value, and the value defaults from 1.
Maintains a variable in the current application instance to hold the current maximum value, and then adds 1 to the primary key each time a primary key value needs to be generated. It is not dependent on the underlying database, so all databases are available.
The principle of generating primary key of increment can infer that this kind of primary key generation policy does not apply to a system with large number of users concurrent access at the same time period, when a large number of users simultaneously insert operation at the same time, there may be the same maximum value and then the same +1. This will cause a primary key conflict. Therefore, this approach must be avoided if there are multiple instance accesses to the same database.
2.Identity
Provides support for built-in identity fields for Db2/mysql,ms SQL Server,sybas and Hypersonicsql. The identifier returned is either a long,short or an int type. Using the SQL Server and MySQL self-increment fields, this method cannot be put into Oracle, Oracle does not support self-increment fields, to set sequence (common in MySQL and SQL Server)
The syntax in the database is as follows:
Mysql:create table t_user (ID int auto_increment PRIMARY key, name varchar (20));
SQL server:create table T_user (ID int identity (primary) key, name varchar (20));
According to the underlying database, to support automatic growth, different databases with different primary key growth mode.
In relation to the underlying database, the database is required to support identity, such as Auto_increment in MySQL, which is identity in SQL Server. The supported databases are MySQL, SQL Server, DB2, Sybase, and Hypersonicsql.
In the construction of the table when the ID is automatic growth, the actual development does not need to define the primary key value inserted into the database, the system will automatically increment a value. The identity does not require hibernate and user intervention, but it is more convenient to use, but because it relies on the database, it is not easy to migrate programs between different databases.
3, Sequence
Use sequence (sequence) in DB2, Postgresql,oracle,sap Db,mckoi, and generator 9generator in InterBase). The identifier returned is either a long,short or an int type.
The syntax in the database is as follows:
Oracle:create sequence Seq_name increment by 1 start with 1;
You can call Seq_name.nextval or seq_name.curval when you need a primary key value, and the database will help us maintain this sequence sequence, guaranteeing that the value is unique each time it is taken, such as:
INSERT into Tbl_name (ID, name) VALUES (seq_name.nextval, ' Jimliu ');
sequence is actually a single-row table.
The principle of implementation: invoking the underlying sequence generated primary key in the database requires the support sequence of the underlying database, so he is dependent on the database .
Supported sequence databases are: Oracle, DB2 (Mysql/sqlserver not supported), POSTGRESQL, sapdb, etc.
Seq_name
If we do not specify the sequence parameter, hibernate accesses a default sequence, which is hibernate_sequence, and we also need to establish this sequence in the database.
In addition, sequence can also have another parameter is paramters, you can see the Hibernate API to understand its usage, see Org.hibernate.id.SequenceGenerator
Call the sequence of the database to generate the primary key, set the sequence name, otherwise hibernate cannot find:
Name_seq (very common in Oracle)
4. Hilo
A long, short, or int type identifier generated using a high/low algorithm, given a table and a field as the source of the high value, the default table is Hibernate_unique_key, and the default field is Next_hi. The high/low algorithm generates identifiers that are unique only in a particular database. It divides the source of the ID into two parts, db+ the memory, and then generates the ID value together by the algorithm, can produce many records in the few connection times, improves the efficiency
Mysql:create table Hi_value (Next_hi integer NOT NULL);
Insert into Hi_value (Next_hi) values (1);
Hi_value
Next_hi
-
Hibernate is responsible for generating low values when hibernate is persisted. The Hilo identifier generator needs to fetch the current value of Next_hi from the Hi_value table when generating the identifier, and then modify the value, which is done in a separate transaction. The maximum low value is configured in the property Max_lo, but when the low value generated in hibernate memory exceeds this value, it is necessary to read the high value again in the Hi_value table of the database.
Using the Hilo build policy, to create an additional table in the database, the default table name is Hibernate_unique_key, the default field is the integer type, and the name is Next_hi ( less)
We can also set our own custom table name and field name .
5, Seqhilo
The combination of sequence and Hilo, Hilo's high position is generated by sequence, so it also requires support from the underlying database
Implemented through the Hilo algorithm, but the primary key history is saved in Sequence and is applicable to databases that support Sequence, such as Oracle (less useful)
6, Increment
This is generated by hibernate in the memory of the primary key, each increment of 1, not dependent on the underlying database, so all the database can be used, but the problem also comes, because it is hibernate generated, so only
Can have a hibernate application process to access the database, otherwise there will be a primary key conflict, can not be used in the cluster situation
Hibernate will add a self-incremented primary key to the primary key when inserting the data, but a hibernate instance maintains a counter, so this method cannot be used when multiple instances are running
7. UUID and GUID
The UUID uses a 128-bit UUID algorithm to generate identifiers of string types, which are unique across a network (using an IP address). The UUID is encoded as a string of 32-bit 16 decimal digits. GUID-generated GUID string in MS SQL Server and MySQL using database
Uuid.hex
Using a 128-bit UUID algorithm to generate the identifier of the string type, the UUID is encoded into a 32-bit 16-digit string. UUID contains: IP address, JVM start time, System time (up to 1/4 seconds), and a counter value (unique in JVM )
Hibernate calculates a 128-bit unique value to insert
Uuid.string
Hibernate calculates a 16-bit value to insert
8, native
Proxy primary key, according to the specific characteristics of the underlying database select the appropriate primary key generation strategy, if it is MySQL or SQL Server, select Identity, if it is Oracle, select sequence.
Depending on the type of database, automatic switching in sequence, identity, and Hilo is more flexible, If you choose sequence or Hilo, The primary key for all tables is taken from Hibernate's default sequence or Hilo table. Also, some databases are not very efficient to support the default primary key generation test
The basis for automatic switching: According to the dialect in the Hibernate configuration file to determine whether Oracle or MySQL, SQL Server, and then for the database type choice sequence or identity as the primary key generation strategy. for Oracle in Sequence mode, for MySQL and SQL Server with identity (self-increment primary key generation mechanism), native is the primary key generation work to the database to complete, hibernate regardless (very common)
Usefulness: Because hibernate uses different mapping methods based on the underlying database, it is flexible and easy to migrate, which can be used if multiple databases are used in a project.
9, assigned
The application is responsible for generating the primary key identifier, often using a primary key in the database that does not have a proxy primary key associated with the business case, which is the default build policy when the <generator> element is not specified. Such as:
This type of primary key generation is not recommended, the database table design should use the proxy primary key (surrogate key), should not use the natural primary key (natural key has business meaning), when the label is not specified, the default is the assigned primary key generation Way
When inserting data, the primary key is added by the user, and hibernate does not care
Function: Used to manually assign the primary key generator, once designated as this, hibernate is not automatically for the Program key generator. When no <generator> tag is specified, the default is how the assigned primary key is generated
Session.save () in the program, before the programmer himself specifies how much the primary key value is.
For example: User.setid (1); This is where programmers manually specify a primary key value of 1 for a user table
10. Select
Use triggers to generate primary keys (primarily for early database primary key generation mechanisms, less)
Ps:
A proxy primary key is a business-independent and uniquely identifiable record in a database, typically a database that is automatically generated, such as MySQL can use auto_increment,sql2000 to generate the identity, and Oracle can use the sequence generation method A natural primary key refers to business-related, user-specified, and uniquely identifies any record in the database.
11, foreign
Used only when a one-to-two correlation mapping based on a shared primary key is applied. That is, the primary key of one object is generated by the primary key of another table referenced. Usually used in conjunction with <one-to-one>.
Summary: Selection of the primary key generation strategy
The UUID is generally recommended because the primary key generation is unique and has no dependency on the database and is highly portable.
The easy-to-use primary key generation mechanism (auto-increase field or sequence) is provided by commonly used databases such as Oracle, DB2, SQL Server, MYSQL, and so on. We can use Native,sequence or identity's primary key generation method on the primary key generation mechanism provided by the database.
It is important to note, however, that some database-provided primary key generation mechanisms may not be as efficient as the optimal number of concurrent insert data, which can cause interlocking between tables.
Therefore, it is recommended to use UUID as the primary key generation mechanism for systems with high concurrent insert requirements.
In short, Hibernate primary key generator selection, but also the specific situation of specific analysis. In general, generating primary keys with UUID will provide the best performance and database platform adaptability.
Hibernate primary key Generation policy