Learn about the different strategies JPA uses to generate the primary key for an entity and at which moment each strategy sets the key value during persistence.

1. Overview

In this tutorial, we’ll illustrate the moment when JPA assigns a value to the primary key. We’ll clarify what the JPA specification says, and then, we’ll show examples using various JPA strategies for primary key generation.

2. Problem Statement

As we know, JPA (Java Persistence API) uses the EntityManager to manage the lifecycle of an Entity. At some point, the JPA provider needs to assign acvalue to the primary key. So, we may find ourselves asking, when does this happen? And where is the documentation that states this?

The JPA specification says:

A new entity instance becomes both managed and persistent by invoking the persist method on it or by cascading the persist operation.

So, we’ll focus on the EntityManager.persist() method in this article.

#jpa #java #developer

When Does JPA Set the Primary Key
1.90 GEEK