Bean Managed Persistence   «Prev  Next»

Lesson 5Finding by Primary Key
ObjectiveUse the primary key to retrieve a persistent entity with JPA.

Finding by Primary Key

In modern applications, entity beans have been replaced by the Java Persistence API (JPA). The recommended way to retrieve an entity is with the EntityManager.find() method. This method takes the entity class and its primary key and returns the managed entity instance or null if no match is found.

Java EE 8 (JPA 2.2)

In Java EE 8, the JPA API resides in the javax.persistence package. Here’s how you can find a Customer entity by its primary key:


  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;

  @Stateless
  public class CustomerService {

      @PersistenceContext
      private EntityManager em;

      public Customer findCustomerById(Long id) {
          return em.find(Customer.class, id);
      }
  }
  

Jakarta EE 10 (JPA 3.1)

Jakarta EE 10 moved JPA to the jakarta.persistence package. The functionality is the same, but the imports change:


  import jakarta.persistence.EntityManager;
  import jakarta.persistence.PersistenceContext;
  import jakarta.ejb.Stateless;

  @Stateless
  public class CustomerService {

      @PersistenceContext
      private EntityManager em;

      public Customer findCustomerById(Long id) {
          return em.find(Customer.class, id);
      }
  }
  



The following two diagrams illustrate how entity retrieval evolved in Java:

  1. The legacy findByPrimaryKey() EJB call chain used in J2EE applications.
  2. The streamlined JPA EntityManager.find() flow used in Java EE 8 and Jakarta EE 10.

Legacy EJB findByPrimaryKey() Call Chain

Legacy EJB findByPrimaryKey call chain: client → home interface → container → ejbFindByPrimaryKey → JDBC lookup → EJBObject or exception
The J2EE approach routes a primary‑key lookup through container callbacks and bean finder methods, returning an EJBObject or throwing a finder‑related exception.


JPA EntityManager.find() Flow (Java EE 8 / Jakarta EE 10)

JPA EntityManager.find flow: client EntityManager.find → persistence context cache → database (if needed) → managed entity or null
The modern JPA approach calls EntityManager.find(), which checks the persistence context first and queries the database if necessary, returning a managed entity instance or null.

How It Works


Example Usage


  Customer customer = customerService.findCustomerById(1001L);
  if (customer != null) {
      System.out.println("Found: " + customer.getName());
  } else {
      System.out.println("Customer not found.");
  }
  

Beyond Primary Keys

In addition to find(), JPA provides query mechanisms such as JPQL and the Criteria API to locate entities by non-primary key attributes. These will be covered in later modules.

Finding Entities - Quiz

Click the quiz link below to test your understanding of using JPA to find entities.
Finding Entities - Quiz


SEMrush Software