Hibernate: Various primary key generation strategies and configuration details

Source: Internet
Author: User
Tags local time sybase

1, assigned

The primary key is generated by an external program and must be specified before save (). Hibernate is not responsible for maintaining primary key generation. It is independent of hibernate and the underlying database, and can be cross-database. Before storing the object, it is necessary to use the setter method of the primary key to assign a value to the primary key, and as to how this value is generated, it is entirely up to you to avoid this method.

<id name= "id" column= "id" >

<generator class= "Assigned"/>

</id>

"UD" is a custom policy name, with an artificially named name, followed by "UD".

Features: Can be cross-database, human control of primary key generation, should be avoided as far as possible.

2, Increment

The maximum value of the primary key is fetched from the database by hibernate (only 1 times per session), based on that value, each increment is 1, the primary key is generated in memory and is not dependent on the underlying database, so it can cross the database.

<id name= "id" column= "id" >

<generator class= "Increment"/>

</id>

Hibernate calls the Generate () method inside the Org.hibernate.id.IncrementGenerator class, using the Select Max (idcolumnname) from TableName statement to get the primary key maximum value. This method is declared as synchronized, so there is no problem inside a standalone Java virtual machine, however, the same value may be fetched when multiple JVMs concurrently access the database select Max, and then insert occurs dumplicate Entry's error. So there can only be one hibernate application process to access the database, otherwise it may produce primary key conflicts, so it is not suitable for multi-process concurrent update database, suitable for a single process to access the database, not for the cluster environment.

Official documents: Use only when no other process is inserting data into the same table, not in the cluster.

Features: cross-database, not suitable for multi-process concurrent update database, suitable for a single process to access the database, not for the cluster environment.

3. Hilo

Hilo (High and low) is the most common form of production in Hibernate and requires an extra table to hold the value of hi. The table that holds the HI value has at least one record (only related to the first record), or an error occurs. can span databases.

<id name= "id" column= "id" >

<generator class= "Hilo" >

<param name= "Table" >hibernate_hilo</param>

<param name= "column" >next_hi</param>

<param name= "Max_lo" >100</param>

</generator>

</id>

<param name= "table" >hibernate_hilo</param> Specifies the name of the table that holds the HI value

<param name= "column" >next_hi</param> Specify column names to hold hi values

<param name= "Max_lo" >100</param> Specify the maximum value of the low

You can also omit the table and column configurations, whose default table is Hibernate_unique_key, which is listed as Next_hi

<id name= "id" column= "id" >

<generator class= "Hilo" >

<param name= "Max_lo" >100</param>

</generator>

</id>

The Hilo generator process for generating a primary key (in the Hibernate_unique_key table, next_hi column example):

1. Get Hi Value: Reads and records the value of the Next_hi field in the database's Hibernate_unique_key table, and the value of this field in the database is saved by 1.

2. Obtain the LO value: from 0 to Max_lo Loop, the difference is 1, the value is Max_lo, and then the LO value continues from 0 to Max_lo Loop.

3. generate the primary key value according to the formula Hi * (Max_lo + 1) + lo calculation.

Note: When the Hi value is 0, then the first value is not 0* (max_lo+1) +0=0, but Lo skips 0 starting from 1, directly 1, 2, 3 ...

How much is the Max_lo configuration appropriate?

This depends on the situation, if the system generally does not restart, and the need to use this table to establish a large number of primary keys, you can max_lo configuration larger, so you can reduce the number of reading data tables, improve efficiency; Conversely, if the server is often restarted, you can max_lo a smaller configuration, You can avoid a large interval between each reboot of the primary key, which causes the primary key value of the primary key to be incoherent.

Features: Cross-database, the flags generated by the Hilo algorithm are guaranteed to be unique only in one database.

4, Seqhilo

Similar to Hilo, the primary key generation mechanism implemented by the HI/LO algorithm simply replaced the data table in Hilo with the sequence sequence, requiring the database to first create sequence for sequence-enabled databases, such as Oracle.

<id name= "id" column= "id" >

<generator class= "Seqhilo" >

<param name= "sequence" >hibernate_seq</param>

<param name= "Max_lo" >100</param>

</generator>

</id>

feature: Similar to Hilo, it can only be used in a database that supports sequences. 5, Sequence

Using the sequence mechanism provided by the database to generate the primary key requires the database to support sequence. Sequence in Oralce, DB, SAP db, Postgersql, Mckoi. MySQL does not support the sequence database (you can use identity).

<generator class= "Sequence" >

<param name= "sequence" >hibernate_id</param>

</generator>

<param name= "sequence" >hibernate_id</param> Specify the name of the sequence

When hibernate generates a primary key, it looks for sequence and assigns it to the primary key value, the primary key value is generated by the database, hibernate is not responsible for maintenance, and you must first create a sequence if you do not specify the sequence name. Use Hibernate's default sequence, named Hibernate_sequence, if you want to create the sequence in the database.

Features: can only be used in a database that supports sequences, such as Oracle.

6. Identity

The identity is generated by the underlying database identifier. The identity is generated by the database itself, but the primary key must be set to self-grow, using identity as a precondition for the underlying database to support autogrow field types such as DB2, SQL Server, MySQL, Sybase, and Hypersonicsql, etc. Oracle does not support this type of field without self-increment.

<id name= "id" column= "id" >

<generator class= "Identity"/>

</id>

Example: If you use a MySQL database, the primary key field must be set to Auto_increment.

ID Int (one) primary key auto_increment

Features: Use only in field databases that support autogrow, such as MySQL.

7, native

Native by hibernate according to the database used by the use of identity, Hilo, sequence one of the primary key generation mode, flexibility is strong. If the identity is supported, the identity is used and sequence is used if sequence is supported.

<id name= "id" column= "id" >

<generator class= "native"/>

</id>

For example, MySQL uses identity,oracle to use sequence

Note: If hibernate automatically selects sequence or Hilo, all table primary keys will be taken from Hibernate's default sequence or Hilo table. Also, some databases are not very efficient in support of the default primary key generation test.

When using sequence or Hilo, you can add parameters, specify sequence names or Hi-value table names, and so on, such as

<param name= "sequence" >hibernate_id</param>

Features: According to the automatic selection of the database, if you use multiple databases in the project, you can use this method, you need to set the table's self-increment field or set up a sequence, establish a table, etc.

8. UUID

uuid:universally unique Identifier, refers to the number generated on a machine, which guarantees that all machines in the same time and space are unique. Based on the standard calculations developed by the Open Software Foundation (OSF), the Ethernet card address, nanosecond time, chip ID code and many possible numbers are used, the standard UUID format is:

Xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12)

Each of these x is a hexadecimal number within the range of 0-9 or a-f.

<id name= "id" column= "id" >

<generator class= "uuid"/>

</id>

Hibernate creates a UUID string as the primary key when saving the object, but it does not have any business logic meaning, only as the primary key, the only drawback length is larger, 32 bits (hibernate will be the middle of the UUID "-" deleted) string, occupy large storage space, But there are two very important advantages, hibernate in maintaining the primary key, do not go to the database query, thereby improving efficiency, and it is a cross-database, and later switching the database is extremely convenient.

Features: UUID length, occupy large space, cross-database, without accessing the database to generate the primary key value, so high efficiency and can guarantee uniqueness, porting is very convenient, recommended use.

9. Guid

guid:globally Unique identifier Global Unique identifier, also known as UUID, is a 128-bit long number, expressed in 16 binary. The core idea of the algorithm is to combine the machine's NIC, local time, and a random number to generate the GUID. Theoretically, if a machine produces 10 million GUIDs per second, it can be guaranteed (in a probabilistic sense) that it will not repeat for 3,240 years.

<id name= "id" column= "id" >

<generator class= "GUID"/>

</id>

Hibernate when maintaining the primary key, query the database first, get a UUID string, which is the primary key value, the value is unique, the disadvantage length is large, the support database is limited, the advantages of the same UUID, cross-database, but still need to access the database.

Note: The length varies depending on the database

36 bits in MySQL using the Select UUID () statement (contains the standard format "-")

In Oracle, 32 bits (without "-") are obtained using the Select Rawtohex (Sys_guid ()) from dual statement

Features: Need database support query UUID, generate the need to query the database, efficiency without UUID high, recommended to use UUID.

10, Foreign

Uses the primary key of another associated object as the primary key for the object. Mainly used in one-to-one relationships.

<id name= "id" column= "id" >

<generator class= "foreign" >

<param name= "Property" >user</param>

</generator>

</id>

<one-to-one name= "user" class= "domain. User "constrained=" true "/>

This example uses domain. The primary key for the user is the primary key for this class of mappings.

Features: Rarely used, mostly in a one-to-one relationship.

11. Select

Using triggers to generate primary keys, mainly used in the early database primary key generation mechanism, can be used in very few places.

12, other annotation mode configuration

Annotation is the same as the bottom implementation of the configuration file, except that the configuration is replaced by a comment method

Autogrow, applicable to databases that support self-increment fields

@Id

@GeneratedValue (strategy = GenerationType. IDENTITY)

Depending on how the underlying database is automatically selected, the settings of the underlying database are required

Like MySQL, the self-increment field is used, and the primary key needs to be set to auto_increment.

@Id

@GeneratedValue (strategy = GenerationType. AUTO)

You can cross a database by using a table to store the generated primary key.

Each time you need a primary key value, query the table named "Hibernate_table" , find the primary key column "GEN_PK " value is "2" record, get this record "Gen_val" value, Based on this value, the primary key value is generated with the value of allocationsize .

@Id

@GeneratedValue (strategy = GenerationType. TABLE, generator = "UD")

@TableGenerator (name = "UD",

Table = "Hibernate_table",

Pkcolumnname = "GEN_PK",

Pkcolumnvalue = "2",

Valuecolumnname = "Gen_val",

InitialValue = 2,

Allocationsize = 5)

Using a sequence to store primary key values

@Id

@GeneratedValue (strategy = GenerationType. SEQUENCE, generator = "UD")

@SequenceGenerator (name = "UD",

Sequencename = "Hibernate_seq",

Allocationsize = 1,

InitialValue = 2)

13. Summary

1 , in order to ensure the uniqueness and immutability of the object identifiers, hibernate should be assigned to the primary key, not the program.

2 , normal use Hibernate maintenance primary key, it is best to set the setter method of the primary key to private, so as to avoid human or program to modify the primary key, and the use of assigned mode, you can not use private, otherwise you can not assign a value to the primary key.

2, Hibernate is the only one of the simplest common primary key generator is the UUID. Although it is a 32-bit hard-to-read long string, but it does not cross-database problems, in the future to switch the database is extremely simple and convenient, recommended use!

3. Automatic growth field type and sequence

Database

Auto Grow Field

Sequence

Mysql

Is

Oracle

Is

DB2

Is

Is

MS SQL Server

Is

Sybase

Is

Hypersonicsql

Is

PostgreSQL

Is

SAP DB

Is

Hsqldb

Is

Infomix

Is

4. Note about the Hilo mechanism:

The flags generated by the Hilo algorithm are guaranteed to be unique only in one database.

Hilo is not available when a user provides a connection to hibernate by itself, or hibernate passes JTA to get a database connection from the application server's data source, as this does not guarantee that Hilo will access the Hi-value table separately in the transaction of the new database connection, in which case, If the database supports sequences, you can use Seqhilo.

5, using the identity, native, Generationtype.auto and other ways to generate the primary key, as long as the use of the self-increment field, the database table field must be set to automatically increase, or error.

6, there are some methods are not listed, such as Uuid.hex,sequence-identity, and so on, these methods are not very common, and has been replaced by other methods, such as Uuid.hex, the official document is not recommended, and the use of the UUID method directly.

7, hibernate version of the primary key generation policy configuration is slightly different, but the implementation is basically the same. For example, some versions default sequence do not specify a sequence name, a sequence named Hibernate_sequence is used, and some versions must specify a sequence name.

8, you can also customize the primary key generation strategy, which is not discussed here for the time being, only discuss the official own generation strategy.

Hibernate: Various primary key generation strategies and configuration details

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.