Hibernate primary key Generation policy

Source: Internet
Author: User
Tags db2

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.  

First, by example to understand the entity mapping file (*.hbm.xml) in the ID generation policy configuration format

Entity class for user User.java

  1. Package com.bjpowernode.hibernate;
  2. Import Java.util.Date;
  3. Public class User {
  4. private String ID;
  5. private String name;
  6. Public User () {}
  7. Public String getId () {
  8. return ID;
  9. }
  10. public void SetId (String id) {
  11. this.id = ID;
  12. }
  13. Public String GetName () {
  14. return name;
  15. }
  16. public void SetName (String name) {
  17. this.name = name;
  18. }
  19. }

User.java corresponding mapping file User.hbm.xml

  1. <? XML version="1.0"?>
  2. <! DOCTYPE hibernate-mapping Public
  3. "-//hibernate/hibernate Mapping DTD 3.0//en"
  4. "Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="Com.bjpowernode.hibernate.User">
  7. <ID name="id">
  8. <generator class="uuid"/>
  9. </ID>
  10. <property name="name"/>
  11. <property name="password"/>
  12. </class>
  13. </hibernate-mapping>

which

<id name= "id" column= "Table primary key field name" Type= "Java.lang.Integer" >

<generator class= "Set Primary key generation policy type"/>

</id>

Second, the principle, characteristics and application of the main key generation strategy commonly used by hibernate

The problem of mapping files next time, the main summary of hibernate commonly used primary key generation strategy.

(1) Increment

A) A new primary key is generated in the form of automatic sequential growth of the primary key value, and the value starts from 1 by default.

b) Principle: Maintain a variable in the current application instance to hold the current maximum value, then add 1 to the primary key each time you need to generate a primary key value. Not dependent on the underlying database, so all databases can be used

c) Disadvantage: the principle of generating primary key by increment can be inferred, this kind of primary key generation policy does not apply to the cluster, a large number of users concurrently access the system at the same time, when a large number of users at the same time period of simultaneous insert operation, there may be the same maximum value and then +1 of the situation, This will cause a primary key conflict. Therefore, this approach must be avoided if there are multiple instance accesses to the same database.

(2) UUID

A) The principle UUID uses the 128-bit UUID algorithm to generate the primary key, which can guarantee the uniqueness of the primary key under the network environment, and can guarantee the uniqueness of the primary key under different database and different server. So that it is used for all databases.

b) features, can guarantee the uniqueness of the primary key in the database, but the generated primary key occupies more storage space

(3) Hilo

A) Principle: through the Hi/lo algorithm (Hilo uses the high-low algorithm to generate the primary key, the low-level algorithm uses a higher value and a low value, and then the algorithm to get two values together) implementation of the primary key generation mechanism, the need for additional database tables to save the primary key generation history state.

b) Features: Additional database tables and fields are required to provide high-level value sources. The table used by default is Hibernate_unique_key, and the default field is called Next_hi. Next_hi must have a record otherwise an error will occur. Additional database table support is required to guarantee the uniqueness of the primary key in the same database, but it does not guarantee the uniqueness of the primary key between multiple databases. The Hilo primary key generation method is maintained by hibernate, so the Hilo approach is not related to the underlying database.

(4) Sequence

A) sequence is actually a single-row table.

b) Implementation principle: 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.

c) databases supporting sequence are: Oracle, DB2 (Mysql/sqlserver not supported), POSTGRESQL, sapdb, etc.

(5) Identity

A) Support auto-growth based on the underlying database, with different primary key growth modes for different databases.

b) Features: related to the underlying database, requires the database to support identity, such as MySQL is auto_increment, SQL Server is identity. The supported databases are MySQL, SQL Server, DB2, Sybase, and Hypersonicsql.

C) Benefits: 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.

(6) native

A) Role: automatically switch between sequence, identity, and Hilo, depending on the type of database.

b) The basis for automatic switching: According to the dialect in the Hibernate configuration file to determine whether it is Oracle or MySQL, SQL Server, and then for the database type choice sequence or identity as the primary key generation strategy.

c) Usefulness: Since hibernate uses different mapping methods based on the underlying database, it is flexible and easy to transplant, which can be used if multiple databases are used in a project.

(7) Assigned

A) 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

b) How to use: Session.save () in the program, before the programmer himself specifies the primary key value.

For example: User.setid (1); This is where programmers manually specify a primary key value of 1 for a user table.

(8) 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.

Summary of dependencies on the database

Uuid,increment, Hilo, Assigned: No dependency on the database

Identity: dependent on MySQL or SQL Server, primary key values are not maintained by hibernate

Sequence: A DBMS that is suitable for supporting sequences such as Oracle, where primary key values are not maintained by hibernate and are generated by sequences.

Native: Select the appropriate primary key generation strategy based on the specific characteristics of the underlying database, if it is MySQL or SQL Server, select Identity, and if it is Oracle, select sequence.

about the 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

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.