Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Generation Type IDENTITY work? How does it know what's the next primary key to insert

Tags:

java

database

jpa

How does Generation Type IDENTITY know whats the next integer to insert in the database when persisting an entity into the DB and in a multi-threaded application(java) is it not possible that two threads get the same primary key for an entity?

like image 206
Nick Div Avatar asked Aug 18 '15 03:08

Nick Div


1 Answers

For @Id attribute, as per this documentation,

There are several strategies for generating unique ids. Some strategies are database agnostic and others make use of built-in databases support. JPA provides support for several strategies for id generation defined through the GenerationType enum values: TABLE, SEQUENCE and IDENTITY.

When one uses IDENTITY strategy, then, database can automatically assign a next value.

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private long id;

Typically, in such cases, column will be of type auto increment.

Please note that the IDs are not generated in Java code, but instead assigned by the underlying database - and databases are built to work with multiple connections wherein a user may be inserting a record in each connection.

On the Java side, each thread will work with one connection - typically such code work with connection pools and borrows a connection from a connection pool - and thus are inherently thread safe.

As per this documentation,

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 PostgreSQL. Oracle does not support IDENTITY columns but its is possible to simulate them using sequence objects and triggers.

like image 147
Wand Maker Avatar answered Sep 28 '22 10:09

Wand Maker