0

So I had been working with Hibernate SessionFactory and its getCurrentSession method for inside a transaction for a while now.

Session session = sessionFactory.getCurrentSession();

and having it interact with other DAO classes within the same test. Switching to JPA though, can I inject a container managed EntityManagerFactory and then replacing the above with

EntityManager entityManager = myFactory.createEntityManager();

and then continue as session interface equivalents in EntityManager in current tests? Performing entityManager.flush() causes

javax.persistence.TransactionRequiredException: no transaction is in progress
1
  • Just inject an EntityManager and call the methods on those. You don't need the EntityManagerFactory and create those yourself. Spring will take care of the transaction and proper injection.
    – M. Deinum
    May 8, 2015 at 19:15

1 Answer 1

1

.flush() call must be part of a transaction. Either you create one or propagate from calling class using @Transactional annotation.

To create:

entityManager.getTransaction().begin();

// Some DB operations

entityManager.flush();
entityManager.getTransaction().commit(); //commit() will do the flush anyway

If you want to to be part of calling class transaction, then include @Transactional annotation either at method or class level depending on design.

2
  • There is no need in flush() right before commit() :) May 8, 2015 at 14:14
  • you are right. Already included that in // java comment. OP wanted to invoke the flush() so just included it.
    – K139
    May 8, 2015 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.