Reputation: 4063
I have an detatched entity and want to set some values. But before that I want to refresh the entity to be sure to have the latest data from the database. I came up with this code. It merges and refreshes my entity before setting some new values.
The problem is, that this creates a new object. Is there a better and simpler way to archieve this?
@Entity
public class MyEntity{
public void setValueAndPersist(){
EntityManager em = ...
em.getTransaction().begin();
MyEntity newEntity = em.merge(this);
em.refresh(newEntity);
newEntity.setSomeVal("someVal");
em.commit();
}
}
Upvotes: 1
Views: 136
Reputation: 2095
Use a own class for interaction with database. DONT do this in the entity itself!
Solution1:
You can use @Version
for current object. https://weblogs.java.net/blog/2009/07/30/jpa-20-concurrency-and-locking . You get a Exception when its not the newest version and you tried to merge it.
Solution2:
You can use find(...)
http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#find%28java.lang.Class,%20java.lang.Object%29
With class and ID from the current Item to load the actual state from DB (or Persistence Context if already exists in it).
Upvotes: 1