Hibernate various primary key generation strategies 2

Source: Internet
Author: User
Tags db2

First look at the label for the primary key mapping:

<id (1) name= "PropertyName" (2) column= "column_name" (3) type= "TypeName" >
(4) <generator class= "Generatorclass"/>
(5) <param name= "Param_name" >param_value</param>
</generator>
</id>

(1)
Identifies the name of the property in the class, and actually corresponds to theSetter/gettermethods that conform to the specificationsJavaclass can write property names directly
(2)
The name of the primary key field in the table
(3)
Hibernatename of the mapping type
(4)
Generatorof the child elementclassproperty, which isJavaclass, this class generates a unique identity for the persisted class, and all generator classes implement theOrg.hibernate.id.IdentifierGeneratorinterfaces, we tend to useHibernatebuilt-in generators, these generators have abbreviated names, these names and their differences are described later
(5)
Configure the configuration values or initialization parameters required by the Generator class

Let's take a look at several commonly used primary key generation methods:
1, automatic growthIdentity:
Suitable forMySQL,DB2,MS SQL Server, using a database-generated primary key forLong, Short,inttype generates a unique identity
UseSQL Serverand theMySQLIncrement field, this method cannot be placed in theOraclein whichOracleself-increment fields are not supported, to setsequence(MySQLand theSQL Serveris often used).
The syntax in the database is as follows:
Mysql:CREATE TABLE t_user (ID intAuto_increment primary key, name varchar (20));
SQL Server:CREATE TABLE t_user (ID intIdentity (primary key, name varchar (20));

<id name= "id" column= "id" type= "long" >
<generator class= "Identity"/>
</id>

2,sequence:
DB2,Oraclesequences that are supported for theLong, ShortorintGenerate unique Identities
The syntax in the database is as follows:
Oracle:Create sequence Seq_name increment by 1 start with 1;
Can be called when a primary key value is requiredSeq_name.nextvalorSeq_name.curvalget, the database will help us maintain thissequencesequence to ensure that the value is unique for each fetch, such as:
INSERT into Tbl_name (ID, name) VALUES (Seq_name.nextval,'Jimliu');

<id name= "id" column= "id" type= "long" >
<generator class= "Sequence" >
<param name= "sequence" >seq_name</param>
</generator>
</id>

If we do not specifysequenceparameter, theHibernatewill access a defaultsequence, ishibernate_sequence, we also need to build this in the databasesequence
In additionsequenceYou can also have another parameter that isparamters, you can viewHibernateof theAPIto understand its usage, seeOrg.hibernate.id.SequenceGenerator
Call the databasesequenceTo generate the primary key, set the sequence name, orHibernateunable to find:
<param name= "sequence" >NAME_SEQ</param>(Oracleis often used).


3,Hilo:
Use a high/the low-level algorithm generatesLong, ShortorintThe identifier of the type, given a table and field as the source of the high value, the default table isHibernate_unique_key, the default field isNext_hi. It willIDthe source of the production is divided into two parts,db+memory, which is then combined with the algorithm to produceIDvalues that can generate multiple records in a very small number of connections, increasing efficiency
Mysql:CREATE TABLE Hi_value (Next_hi integer NOT null);

Insert into Hi_value (Next_hi) values (1);

<id name= "id" column= "id" >
<generator class= "Hilo" >
<param name= "Table" >hi_value</param>
<param name= "column" >next_hi</param>
<param name= "Max_lo" >100</param>
</generator>
</id>

InHibernatewhen persisted, theHibernateresponsible for generating low values. HiloThe identifier generator needs to generate identifiers from theHi_valueout of the tableNext_hi's current value, and then modifies the value, which is done in a separate transaction. The maximum low value in the propertyMax_loIn the configuration, but in theHibernatewhen the low value generated in memory exceeds this value, there is a need to go to the databaseHi_valueThe high value is read again in the table.
UseHilobuild a policy to create an additional table in the database with the default table nameHibernate_unique_key,Default Fieldintegertype, name isNext_hi(less used)
We can also set our own custom table name and field name.
<id name= "id" type= "integer" >
<column name= "id"/>
<generator class= "Hilo" >
<param name= "My_unique_key"/>
<param column= "Next_hi"/>
</generator>
</id>


4,native:
Based on the ability of the underlying database, fromIdentity,sequence,HiloSelect one of theand more flexibility, but at this point, if you choosesequenceorHilo, all of the table's primary keys will beHibernatethe defaultsequenceorHilothe table is taken. Also, some databases are not very efficient to support the default primary key generation test
ForOracleAdoptSequenceWay, forMySQLand theSQL ServerAdoptIdentity(self-increment primary key generation mechanism),nativeis to get the primary key generation done to the database,Hibernateno matter (very often)

<id name= "id" column= "id" >
<generator class= "native"/>
</id>

5,Seqhilo:
Sequenceand theHilothe combination,Hilothe high level bysequencesupport for the underlying database is also required.
PassHiloalgorithm is implemented, but the primary key history is saved inSequence, which is applicable to supportSequencethe database, such asOracle(less used)

<id name= "id" column= "id" >
<generator class= "Seqhilo" >
<param name= "sequence" >seq_name</param>
<param name= "Max_lo" >100</param>
</generator>
</id>

6,increment:
This is generated by Hibernate in memory of the primary key, each increment of 1, do not rely on the underlying database, so all the database can be used, but the problem comes with, because it is Hibernate is generated, so only

can have aHibernateThe application process accesses the database, otherwise there will be a primary key conflict and cannot be used when inserting data in the case of a clusterHibernateadds a self-increment primary key to the primary key, but aHibernateThe instance maintains a counter, so this method cannot be used when multiple instances are running
<id name= "id" column= "id" >
<generator class= "Increment"/>
</id>

7,Uuid.hex:
Use a128-bitof theUUIDthe algorithm generates an identifier for the string type,UUIDis encoded into a +bit -a string of binary digits. UUIDincludes:IPaddress,JVMstart time, System time (accurate to Quarterseconds) and a

Counter value ( unique in JVM )
Hibernate calculates The unique value of a

<id name= "id" column= "id" >
<generator class= "Uuid.hex"/>
</id>


Uuid.string
Hibernate calculates a value of one of the digits inserted


8,assigned:
It is the responsibility of the application to generate primary key identifiers, often using a primary key that does not have a proxy primary key in the database, for business-related situations, such as:

<id name= "id" column= "id" type= "string" >
<generator class= "Assigned"/>
</id>

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), in the absence of the specified <generator> tags,

The default is how the assigned primary key is generated
When inserting data, the primary key is added by the user, andhibernate does not care


9,foreign
Use fields from external tables as primary keys

Ten,Select
Use triggers to generate primary keys (primarily for early database primary key generation mechanisms, less)


In addition, some tables do not have a proxy primary key, using federated primary keys, multiple fields are unique, which is also not recommended for table design, but if encountered in the project, you can refer to hibernate Official document Composite-id Part of the introduction

Hibernate various primary key generation strategies 2

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.