Merge and Remove

Updating a Managed Entity: No Method Needed

@Transactional
public void changePrice(Long id, BigDecimal newPrice) {
    Product p = em.find(Product.class, id);   // managed
    p.setPrice(newPrice);                     // that's it - no em.update() exists
}                                             // commit -> UPDATE products set ... where id=?

JPA has no update() method. Changes to managed entities are detected at flush time (dirty checking, next module).

merge(): Bring Outside Data Back In

merge is for objects that are not managed — typically a detached entity from an earlier transaction, or an object built from a request. It copies the state onto a managed instance and returns that managed instance:

@Transactional
public Product update(Product detached) {          // e.g. built from a PUT request body, id = 42
    Product managed = em.merge(detached);          // SELECT by id, then copy fields onto it
    // managed != detached
    // changing 'detached' after this line does NOTHING; use 'managed'
    return managed;
}

Log

PUT /api/products/42

Example output

Hibernate: select p1_0.id,p1_0.category,...,p1_0.stock from products p1_0 where p1_0.id=?
Hibernate: update products set category=?,description=?,name=?,price=?,status=?,stock=? where id=?

Note: If you merge an object with every field taken from a request, any field the client did not send becomes null in the database. The safer pattern for APIs: find the entity, then copy only the allowed fields from a DTO.

remove(): Delete

@Transactional
public void delete(Long id) {
    Product p = em.find(Product.class, id);      // must be managed
    if (p != null) em.remove(p);                 // DELETE runs at flush/commit
}

// Wrong: remove() on a detached object
em.remove(detachedProduct);   // IllegalArgumentException: Removing a detached instance in.shopease.entity.Product#42
delete from products where id=?

Other Useful Methods

MethodWhat it does
flush()Sends pending INSERT/UPDATE/DELETE to the database now (transaction stays open)
detach(entity)Removes one entity from the persistence context; its changes are no longer tracked
clear()Detaches everything; useful in batch jobs to free memory
contains(entity)true if the object is managed by this EntityManager
refresh(entity)Reloads the state from the database, overwriting unsaved changes
createQuery(jpql)Runs a JPQL query (medium level)