Saving entity in repository does not work SPRING

孤者浪人 提交于 2019-12-04 02:31:13
Phoenix VN

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!