Learning Hibernate and JPA's primary key generation strategies using annotation styles

Source: Internet
Author: User
Tags generator one table mysql database oracle database

A primary key is a basic concept in a relational database that is used to guarantee the uniqueness of a record. In simple terms, it is the same database table where multiple records with the same primary key are not allowed. The primary key generation strategy is how the primary key of this record is generated when a record is inserted into a database table. In most cases, the primary key has no business meaning, so the developer does not, and does not need, to set the primary key value of the entity object. But for a database, the primary key is necessary, and obviously this responsibility falls on the persistence layer of hibernate. For beginners hibernate people, often will be dizzy by a bunch of primary key generation strategy, this article introduces some confusing concepts, hoping to help you understand Hibernate primary key generation strategy.

Hibernate includes a number of primary key generation strategies, which can be divided into two categories: one is the JPA standard primary key generation strategy, and the other is the Hibernate framework-specific primary key generation strategy. There are 4 JPA standard strategies: auto policy, table policy, sequence policy, identity policy, and the rest is Hibernate's own strategy, including our common native, UUID, assigned, sequence, etc. the difference between 1.JPA and hibernate

The JPA full name Java Persistence API is a technical specification for ORM Technology by Sun, which is used to persist pojo in a standard manner, similar to the JDBC specification. Hibernate was first developed in an ORM framework to solve the problem of JDBC. With the development and refinement of the JPA standard, Hibernate has since supported the JPA specification and is fully compatible with the JPA specification. It also says that Hibernate is an implementation of the JPA standard and adds some of its own unique features. This is what we often say: JPA is a subset of Hibernate, and Hibernate is a superset of JPA. 4 Strategies introduced in 2.JPA Auto Policy

The AUTO policy is the JPA default policy, defined in Hibernate's code Generationtype.auto. Using the AUTO policy is the decision to give the primary key generated policy to the persistence engine (persistence engine), which chooses the most appropriate from the Table policy, Sequence policy, and identity policy three strategies. Different persistence engines, different database general policies are different. For example, Oracle most commonly used is the sequence,mysql most commonly used is identify, because the Oracle database supports sequence, and the MySQL database is only supported auto_increment. Sequence Strategy

Corresponds to the Hibernate code generationtype.sequence. Some databases, such as Oracle, will have a "sequence builder" built in. In order to use the sequence, we need to use the JPA sequence strategy. Identity Policy

Corresponds to the Hibernate code generationtype.identity. This is a good fit for databases like MySQL and provides support for self-increasing primary keys. Table Policy

Corresponds to the Hibernate code generationtype.table . Use a special database table to save the primary key value that is required when inserting records. 3. Annotation style using the JPA primary key generation policy to configure the entity primary key generation strategy, you need to use the Auto policy with the @generatedvalue primary key

The corresponding Java code is as follows:

public class Teacher
{
  private int id;
  Private String title;

  @Id
  @GeneratedValue (strategy = generationtype.auto) public
  int getId ()
  {
    return Id;
  }
}
I am using MySQL corresponding database table as follows:
Attention:

1, if it is a MySQL database, you must set the primary key column to self-growth, or use auto policy, will be error:

Org.hibernate.exception.GenericJDBCException:Field ' id ' doesn ' t has a default value

2, if it is an Oracle database, then will use Hibernate_sequence, the name is fixed, cannot be changed. using the sequence policy

public class Teacher
{
  private int id;
  Private String title;

  @Id
  @GeneratedValue (strategy = generationtype.sequence,generator= "Myseqgenerator")
  @SequenceGenerator ( Name = "Myseqgenerator", Sequencename = "T_teacher_sequence", InitialValue = +, allocationsize = () public
  int get ID ()
  {
    return ID;
  }
}
Here, you need to use @sequencegenerator to specify information about the sequence.

Name: the names of the sequence generators, which are referenced in @generatedvalue

Sequence generator name in the Sequencename:oracle database

InitialValue: Initial value of primary key

Allocationsize: The size of each growth value of the primary key

Note: If the underlying database does not execute the sequence, an error is noted:

Org.hibernate.MappingException:org.hibernate.dialect.MySQLDialect does not support sequences using identity policy

public class Teacher
{
  private int id;
  Private String title;

  @Id
  @GeneratedValue (strategy = generationtype.identity) public
  int getId ()
  {
    return Id;
  }
}
Use is relatively simple, there is no need to do a detailed introduction using the table policy
public class Teacher
{
  private int id;
  Private String title;

  @Id
  @GeneratedValue (strategy = generationtype.table,generator= "Mytablegenerator")
  @TableGenerator (name = " Mytablegenerator ", table =" Hibernateneedtable ", 
          pkcolumnname =" Pk_key ", Valuecolumnname =" Pk_value ", Pkcolumnvalue = "Teacherid", 
          InitialValue = +, allocationsize = +) public
  int getId ()
  {
    return ID;
  }
}
I don't know how to describe the meaning of these attributes in the right language. Directly on the graph and executed SQL statements, the reader can understand the meaning of these attributes simply by understanding them.

1, we have more than one table in the database

2, the actual SQL statement issued as follows:

Hibernate: 
  Select
    pk_value 
  from
    hibernateneedtable 
  where
    pk_key = ' Teacherid ' for update
      
Hibernate: 
  update
    hibernateneedtable 
  set
    pk_value =? 
  where
    Pk_value =? 
    and Pk_key = ' Teacherid '
Hibernate: 
  insert 
  into
    Teacher
    (title, id) 
  values
    (?,?)
See here, you should understand the use of these attributes. It is worth mentioning that this table can give an infinite number of tables as the primary key table, just add a record (need to ensure that table, Pkcolumnname, valuecolumnname three attribute values are unique.

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.