Hibernate Primary Key Generation Policy

Source: Internet
Author: User

Hibernate Primary Key Generation Policy

The primary key generation policy provided by Hibernate allows us to set keywords in the ing xml file of object classes to tell hibernate how to generate primary keys, then hibernate completes the primary key control of the database according to the settings.

Principles, features, and application scenarios of common primary key generation policies of Hibernate:

 

1. increment

 

The proxy primary key used to generate a unique identifier for long, short, or int type. Data can be used only when no other process inserts data into the same table. Do not use it in a cluster. The primary key auto-increment maintained by hibernate is irrelevant to the underlying database, but it is not suitable for two or more hibernate processes.

Generate a new primary key in an auto-increment sequence. The value starts from 1 by default.

Maintain a variable in the current application instance to save the current maximum value. Then, each time you need to generate a primary key value, add 1 as the primary key. it does not depend on the underlying database, so all databases can be used.

The principle of generating a primary key through increment can be inferred that this primary key generation policy is not applicable to clusters and systems with a large number of concurrent user accesses at the same time period. When a large number of users perform the insert operation at the same time period, A primary key conflict may occur when the same maximum value is obtained and the value is plus 1 at the same time. Therefore, if the same database has multiple instances to access, this method must be avoided.

2. identity

Supports built-in identity fields for DB2/MySQL, ms SQL Server, Sybas, and HypersonicSQL. The returned identifier is of the long, short, or int type. Use auto-increment fields of SQL Server and MySQL. This method cannot be placed in Oracle. Oracle does not support auto-increment fields. You need to set sequence (it is often used in MySQL and SQL Server)
The database syntax 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 (1, 1) primary key, name varchar (20 ));

Supports automatic growth based on the underlying database. Different databases use different primary key growth methods.

It is related to the underlying database and requires that the database support Identity. For example, in MySQl, It is auto_increment and in SQL Server, It is Identity. Supported databases include MySql, SQL Server, DB2, Sybase, and HypersonicSQL.

When creating a table, the id is specified to automatically increase. In actual development, you do not need to define the primary key value for database insertion. The system automatically increments the value sequentially. Identity does not require Hibernate and user interference and is easy to use. However, because it depends on the database, it is not easy to transplant programs between different databases.

3. sequence

 

Use sequence in DB2, PostgreSQL, Oracle, sap db, and McKoi, while use generator 9 generator in InterBase ). The returned identifier is of the long, short, or int type.
The database syntax is as follows:
Oracle: create sequence seq_name increment by 1 start with 1;
When you need a primary key value, you can call seq_name.nextval or seq_name.curval to obtain it. The database will help us maintain this sequence and ensure that each retrieved value is unique, for example:
Insert into tbl_name (id, name) values (seq_name.nextval, 'jimliu ');

Sequence is actually a single row, single column table.

Implementation principle: calls the sequence at the underlying layer of the database to generate a primary key, which requires the support sequence of the underlying database, so it depends on the database.

Databases Supporting sequence include Oracle, DB2 (not supported by Mysql/SQlServer), PostgreSql, and SAPDb.

Seq_name

If the sequence parameter is not specified, Hibernate will access a default sequence, which is hibernate_sequence. We also need to create this sequence in the database.
In addition, sequence can have another parameter paramters. You can view the Hibernate API to understand its usage. For details, see org. hibernate. id. SequenceGenerator.
Call the database sequence to generate the primary key. You need to set the sequence name. Otherwise, hibernate cannot find it:
NAME_SEQ (common in Oracle)

 

4. hilo

Long, short, or int type identifiers generated using a high/low level algorithm. A table and field are given as the source of the high value. The default table is hibernate_unique_key, and the default field is next_hi. The identifier generated by the high/low algorithm is unique only in a specific database. It divides the id source into two parts, DB + memory, and then generates the id value together according to the algorithm. Multiple records can be generated within a few connections, improving efficiency.

MySQL: create table hi_value (next_hi integer not null );

Insert into hi_value (next_hi) values (1 );

Hi_value
Next_hi
100

During hibernate Persistence, hibernate is responsible for generating low-level values. When the hilo identifier generator generates the identifier, it needs to retrieve the current value of next_hi from the hi_value table, and then modify the value. This operation is completed in a separate transaction. The maximum low value is configured in the max_lo attribute, but when the low value generated in the Hibernate memory exceeds this value, you need to read the high value again in the hi_value table of the database.
To use the hilo generation policy, create an additional table in the database. The default table name is hibernate_unique_key. The default field is of the integer type and the name is next_hi (rarely used)
You can also set the custom table name and field name.

5. seqhilo

With the combination of sequence and hilo, the high level of hilo is generated by sequence, so it also needs the support of the underlying database.
Implemented through the hilo algorithm, but the primary key history is stored in Sequence. It is suitable for databases that support Sequence, such as Oracle (rarely used)

6. increment

This is the primary key generated by Hibernate in the memory. Each increment is 1 and does not depend on the underlying database. Therefore, all databases can be used, but the problem also arises, because it is generated by Hibernate, only

A Hibernate application process can access the database. Otherwise, a primary key conflict occurs and cannot be used in a cluster.
Hibernate adds an auto-incrementing primary key to the primary key when inserting data, but a hibernate instance maintains a counter. Therefore, this method cannot be used when multiple instances are running.

7. UUID and GUID

UUID uses a 128-bit UUID algorithm to generate string-type identifiers, which are unique in a network (using IP addresses ). UUID is encoded as a 32-bit hexadecimal number string. The GUID generated by the database is used in ms SQL Server and MySQL.

Uuid. hex

A 128-bit UUID algorithm is used to generate a string-type identifier. UUID is encoded into a 32-bit hexadecimal number string. UUID includes: IP address, JVM start time, system time (accurate to 1/4 seconds), and a counter value (unique in JVM)
Hibernate calculates a 128-bit unique value insert.

Uuid. string
Hibernate calculates a 16-Bit Insert value.

8. native

Proxy primary key. select an appropriate primary key generation policy based on the specific characteristics of the underlying database. For mysql or sqlserver, Select identity. For oracle, select sequence.

Automatically switches between sequence, identity, and hilo based on the database type, providing higher flexibility. If sequence or hilo is selected, the primary keys of all tables are retrieved from the default sequence or hilo table of Hibernate. In addition, some databases support the test of primary key generation by default, and the efficiency is not very high.

The basis for automatic switch: Determine whether it is Oracle, Mysql, or SqlServer Based on the Dialect in the Hibernate configuration file, and then select sequence or identity as the primary key generation policy for the database type. For oracle using Sequence, For MySQL and SQL Server using identity (auto-incrementing primary key generation mechanism), native is to submit the primary key generation work to the database, hibernate (very common)

Usage: Because Hibernate uses different ing methods based on the underlying database, it is highly flexible and convenient for program transplantation. This method can be used if multiple databases are used in the project.

9. assigned

The application is responsible for generating the primary key identifier, which is often used in the database without a proxy primary key. The primary key used is business-related. This is The element does not specify the default generation policy for timing. For example:

This primary key generation method is not recommended. When designing a database table, you should use a proxy primary key (surrogate key) instead of a natural primary key (natural key has business meaning ), if no tag is specified, the default mode is assigned primary key generation.
When inserting data, the primary key is added by the user, and hibernate does not

Function: it is used to manually allocate a primary key generator. Once this is specified, Hibernate will not automatically create a primary key generator for the program. Not Specified The default value is the assigned primary key generation method.

Before session. save (); in a program, the programmer specifies the value of the primary key.

For example: user. setId (1); in the program, the programmer manually specifies the primary key value as 1 for the user table.

10. select

 

Use a trigger to generate a primary key (mainly used to generate a primary key for an earlier database, with less use)

Ps:

The proxy primary key is a record that is not related to the business and can uniquely identify the database. Generally, it is automatically generated by the database. For example, mysql can use auto_increment and Sql2000 can use identity generation, oracle can use sequence to generate a natural primary key, which is business-related. It is specified by the user and uniquely identifies any record in the database.

11. foreign

 

Only applicable to one-to-one association ing based on shared primary keys. That is, the primary key of an object is generated by referring to the primary key of another table. Normally Used together.


Summary: Primary Key Generation Policy Selection

 

Generally, UUID is recommended because the primary key is generated only and has no dependency on the database, which is highly portable.

Common databases, such as Oracle, DB2, SQLServer, and MySql, provide an easy-to-use primary key generation mechanism (Auto-Increase field or Sequence ). We can use native, sequence, or identity primary key generation methods in the primary key generation mechanism provided by the database.

However, it is worth noting that the primary key generation mechanism provided by some databases may cause inter-Table locks when a large amount of concurrent insert data is not optimal in terms of efficiency.

Therefore, for systems with high requirements for concurrent Insert, uuid is recommended as the primary key generation mechanism.

In short, you need to analyze the selection of the hibernate primary key generator. Generally, using uuid to generate a primary key provides the best performance and database platform adaptability.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.