'How to remove entity with first level cache and JPA in one open session?
In my persistence layer i have remove method that will remove the entities in removed state and EntitySession to commit the changes.
- The
EntitySession
transaction = entityManager.getTransaction();
- The remove method
public BehindCacheBuilder<R, V> remove(Object object) {
entityManager.remove(object);
return this;
}
- And committing the transaction
transaction.commit();
But when i execute the method nothing will remove from datasource.
Solution 1:[1]
Like any write-behind cache the Persistence context requires flushing (in your case committing, which is different than flushing) in order to synchronize the in-memory persistence state with underlying datasource.
Thus firstly make sure your entities that you want to remove be present in Managed state from first place then try to remove to change the state for delating the entity after flushing (committing) .
public BehindCacheBuilder<R, V> remove(Class<?> type, Object object) {
entityManager.remove(entityManager.find(type, object));
return this;
}
Which in here we bring the entity that we want to remove to Managed state.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lunatic |

