Persist and Find

Getting an EntityManager

// Spring Boot: inject it. Spring gives you a thread-safe proxy that
// points to the EntityManager of the current transaction.
@Repository
public class ProductDao {

    @PersistenceContext
    private EntityManager em;

    // or constructor injection:  public ProductDao(EntityManager em) { this.em = em; }
}

Note: Changes to the database must happen inside a transaction. In Spring put @Transactional on the service method; without Spring use em.getTransaction().begin() / commit().

persist(): Save a New Entity

@Transactional
public Long addProduct() {
    Product p = new Product("SKU-BOAT-450", "Boat Rockerz 450",
                            new BigDecimal("1499.00"), 120, "Electronics");
    em.persist(p);                 // p is now managed
    return p.getId();              // IDENTITY: insert already ran, id is set
}

Log

POST /api/products

Example output

Hibernate: insert into products (category,created_at,description,name,price,sku,status,stock) values (?,?,?,?,?,?,?,?)
TRACE o.h.orm.jdbc.bind : binding parameter (1:VARCHAR) <- [Electronics]
TRACE o.h.orm.jdbc.bind : binding parameter (4:VARCHAR) <- [Boat Rockerz 450]
TRACE o.h.orm.jdbc.bind : binding parameter (5:NUMERIC) <- [1499.00]
  • persist returns void; the object you passed becomes managed.
  • With IDENTITY the INSERT runs immediately (the id comes from the database). With SEQUENCE the INSERT waits until flush/commit.
  • Calling persist on an object that already has a database id (a detached entity) throws EntityExistsException / "detached entity passed to persist".

find(): Load by Primary Key

Product p = em.find(Product.class, 42L);
if (p == null) {
    throw new ProductNotFoundException(42L);    // find returns null when no row exists
}
select p1_0.id, p1_0.category, p1_0.created_at, p1_0.description, p1_0.name,
       p1_0.price, p1_0.sku, p1_0.status, p1_0.stock
from products p1_0
where p1_0.id=?

getReference(): A Lazy Placeholder

Product ref = em.getReference(Product.class, 42L);   // no SQL yet: a proxy with only the id
cartItem.setProductId(ref.getId());                  // still no SQL
String name = ref.getName();                         // now SELECT runs;
                                                     // EntityNotFoundException if row 42 does not exist
findgetReference
SQLImmediately (unless in context)Only when a non-id field is used
Row missingReturns nullThrows EntityNotFoundException on access
Use whenYou need the dataYou only need it to set a relationship (medium level)