n_g
n_g

Reputation: 3545

@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?

Upvotes: 48

Views: 57422

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340993

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.

Upvotes: 76

Related Questions