因此,我在事务内部使用 Hibernate SessionFactory
及其 getCurrentSession
方法已经有一段时间了。
Session session = sessionFactory.getCurrentSession();
并让它与同一测试中的其他 DAO 类交互。不过,切换到 JPA 后,我可以注入(inject)一个容器管理的 EntityManagerFactory ,然后将上面的内容替换为
EntityManager entityManager = myFactory.createEntityManager();
然后在当前测试中继续作为 EntityManager
中的 session 接口(interface)等效项?执行 entityManager.flush()
会导致
javax.persistence.TransactionRequiredException: no transaction is in progress
最佳答案
.flush()
调用必须是事务的一部分。您可以创建一个,也可以使用 @Transactional
注释从调用类进行传播。
创建:
entityManager.getTransaction().begin();
// Some DB operations
entityManager.flush();
entityManager.getTransaction().commit(); //commit() will do the flush anyway
如果您想成为调用类事务的一部分,请根据设计在方法或类级别包含 @Transactional
注释。
关于java - SessionFactory.getCurrentSession() 与 EntityManager.createEntityManager(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125633/