0
我不能做一個簡單的創建/刪除工作,跨事務。我使用Spring/JPA/Hibernate,沒有ehcache。休眠/ JPA簡單的創建/刪除實體
我的實體類用戶,並MyDao與Spring的@Transactional(我的理解@Transactional應該是服務,這裏只是簡化我的情況)
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); } }
我的測試標誌着兩種方法:
{ 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 ..." }
根據Hibernate,session.delete()可以刪除detached或managed。但爲什麼失敗?
感謝您的幫助
邁克爾