Saving entity in repository does not work SPRING Saving entity in repository does not work SPRING spring spring

Saving entity in repository does not work SPRING


For starter, you're actually working on 2 different EntityManager in your non-working test case:

  1. EntityManager autowired into your test by Spring (this one is singleton and should be avoided anyway) ,other is
  2. EntityManager created by the EntityManagerFactory configured in your ApplicationConfiguration.

At the same time, you also have another Session running along side the aforementioned 2 EntityManagers due to your configuration of Hibernate SessionFactory. Additionally, because of the configured HibernateTransactionManager, all transactions created by @Transactional are bound to the Hibernate's Session created by SessionFactory and the EntityManager used by your Repository certainly has no way to know about it. This is why TransactionRequiredException was thrown when your Repository tried to persist data.

To fix it, you may consider removing the Hibernate's SessionFactory and switch the transaction manager to a JpaTransactionManager. Then, @Transactional on your Repository will have the effect of creating a new transaction and binding it to the existing EntityManager that is known to Spring.

One side note is that the @Transactional on your TestClass doesn't help at all as the instance of this class is not instantiated and managed by Spring. To make this work, a proper configuration of transactional test class needs to be provided as described here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html.

Hope this helps.