[英]Hibernate + Spring: javax.persistence.TransactionRequiredException: no transaction is in progress
I'm currently setting up a project with Spring and Hibernate.我目前正在使用 Spring 和 Hibernate 建立一个项目。 After several other problems i got the next problem :P在其他几个问题之后,我遇到了下一个问题:P
Anyway.反正。 When call entityManager.flush()
I get an exception: javax.persistence.TransactionRequiredException: no transaction is in progress
.当调用entityManager.flush()
我得到一个异常: javax.persistence.TransactionRequiredException: no transaction is in progress
。
I have annotated my class with @Transactional
but it's still not working.我已经用@Transactional
注释了我的课程,但它仍然无法正常工作。
I read serval threads here where people had a similar problem, but the solution was always <tx:annotation-driven transaction-manager="transactionManager" />
.我在这里阅读了人们遇到类似问题的 serval 线程,但解决方案始终是<tx:annotation-driven transaction-manager="transactionManager" />
。 But I already have this configuration.但是我已经有了这个配置。
I am not sure what code or files I should provide you, so you can find the whole project here: https://drive.google.com/file/d/0B7Exc4dHICl-UDN3ZEJnbS1FZFk/edit?usp=sharing我不确定我应该提供什么代码或文件,所以你可以在这里找到整个项目: https : //drive.google.com/file/d/0B7Exc4dHICl-UDN3ZEJnbS1FZFk/edit?usp=sharing
Thank you in advance.先感谢您。
Here is post about config when @Transactional
is not working - do you have tag <context:component-scan>
in appContext.xml
set? 这是关于@Transactional
不工作时的配置的帖子 - 你在appContext.xml
设置了标签<context:component-scan>
吗? This both scans packages for beans to register and activates annotation.这既扫描包中的 bean 以注册并激活注释。 If you don't have a <context:component-scan>
the @Transactional
annotation will not wrapp the method in a transaction.如果你没有一个<context:component-scan>
的@Transactional
注解不会wrapp在事务的方法。
I have found solution of this issue by implementing ApplicationListener<ContextRefreshedEvent>
and putting a self reference to the service call.我通过实现ApplicationListener<ContextRefreshedEvent>
并把自引用放到服务调用中,找到了这个问题的解决方案。
The issue arise because there is no transaction started in the calling method and since subsequent method calls are internal reference so no new transaction was created.出现问题是因为调用方法中没有启动事务,并且后续方法调用是内部引用,因此没有创建新事务。 So, I have to either make my calling method as transactional or create an internal reference and call the subsequent method through that reference.因此,我必须要么将我的调用方法设为事务性,要么创建一个内部引用并通过该引用调用后续方法。
You have to override the following method as您必须将以下方法覆盖为
private MyService myService = myService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
myService = event.getApplicationContext().getBean(MyService.class);
}
Then use myService.myMethod()
instead of myMethod()
where ever you want transaction to be active.然后在您希望事务处于活动状态的地方使用myService.myMethod()
而不是myMethod()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.