I cannot make a simple create/delete to work, across transactions. I use Spring/JPA/Hibernate, no ehcache.
My entity class User, and MyDao with two methods marked by Spring's @Transactional (I understand @Transactional should be on service, here is just simplify my case)
public class MyDao { @PersistenceContext private EntityManager entityManager; @Transactional public void create(User user) { entityManager.persist(user); entityManager.refresh(user); } @Transactional public void delete(User user) { // Since user maybe detached, I use Hibernate to delete. Session sess = entityManager.unwrap(Session.class); sess.delete(user); } }
My test:
{ User user = new User(); myDao.create(user); // above is ok. user created with generated ID. // and I assume the transaction is closed, so user is detached myDao.delete(user); // above failed with error "Removing a detached instance ..." }
According to Hibernate, session.delete() can delete either detached or managed. But why it failed?
Thanks for help
Michael