Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@GeneratedValue(strategy="IDENTITY") vs. @GeneratedValue(strategy="SEQUENCE")

I'm new to hibernate. I do not understand the the following two primary key generation strategies:

  1. Identity
  2. Sequence

Can someone please explain how these two work and what is the difference between these two?

like image 964
n_g Avatar asked Jan 21 '12 17:01

n_g


People also ask

What is difference between sequence and identity?

The IDENTITY property is tied to a particular table and cannot be shared among multiple tables since it is a table column property. On the flip side the SEQUENCE object is defined by the user and can be shared by multiple tables since is it is not tied to any table.

What is @GeneratedValue strategy GenerationType identity?

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql , you may specify auto_increment in the definition of table to make it self-incremental, and then use @GeneratedValue(strategy = GenerationType.IDENTITY)

What is GenerationType sequence?

GenerationType. SEQUENCE in hibernate generates the sequence for the primary column of the table. We need to create a sequence generator in database and refer that name in the code. The syntax of GenerationType.

What is the default strategy of of GeneratedValue?

AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability. SEQUENCE: Tells Doctrine to use a database sequence for ID generation.


1 Answers

Quoting Java Persistence/Identity and Sequencing:

Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.

In plain English: you mark at most one ID column in your table as IDENTITY. The database engine will put next available value for you automatically.

And:

Sequence objects use special database objects to generate ids. Sequence objects are only supported in some databases, such as Oracle, DB2, and Postgres. Usually, a SEQUENCE object has a name, an INCREMENT, and other database object settings. Each time the <sequence>.NEXTVAL is selected the sequence is incremented by the INCREMENT.

Sequences are more flexible and slightly more complex. You define an extra object in your database next to tables, triggers, etc. called sequences. Sequences are basically named counter you can use anywhere inside queries.

like image 200
Tomasz Nurkiewicz Avatar answered Sep 25 '22 15:09

Tomasz Nurkiewicz