tproenca
tproenca

Reputation: 146

Refresh entities in JPA

I'm confused about how I should refresh the state of entity that is already in the database. Being more specific, suppose I have "entity" persisted with a code like this:

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
entityManager.close();

Since I closed the EntityManager my entity instance is detached. Now suppose that I have other objects using this instance of entity. If I want to fetch the new state of this entity from the database, I pretty much can't use em.refresh() because the entity is detached. The em.merge() method returns a managed instance, and since is not the same instance of my object this can be a problem. I can foresee two solutions:

  1. create a new method in my entity object that updates its state using a given entity instance.
  2. not close the entity manager (implications !??)

So, what I should do in this case? How can I refresh the state of my entity object without losing all the references from other objects to it? Ideas?

Upvotes: 4

Views: 3096

Answers (2)

eastwater
eastwater

Reputation: 5572

If entity A references entity B that is detached, merging B returns B', and refresh B'. If you merge A, A will change its reference of B to B'.

A ---> B --(merge)--->B'
                    (refresh)
                    /
merge A -----------/

Upvotes: 1

Nayan Wadekar
Nayan Wadekar

Reputation: 11602

To avoid the changes being made to an entity by refreshing & getting detached after persisting, can implement the Cloneable interface & then processing the cloned entity accordingly.

//---

XEntity cloneX = (XEntity) entity.clone();

cloneX = entityManager.merge(cloneX);/* Persisting & getting synchronized copy */ 
// entityManager.refresh(cloneX); /* not need */

cloneX.copyTo(entity); // Add required changes back to entity if any

//---

Upvotes: 0

Related Questions