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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With