简体   繁体   中英

Hibernate + Spring: javax.persistence.TransactionRequiredException: no transaction is in progress

I'm currently setting up a project with Spring and Hibernate. After several other problems i got the next problem :P

Anyway. When call entityManager.flush() I get an exception: javax.persistence.TransactionRequiredException: no transaction is in progress .

I have annotated my class with @Transactional but it's still not working.

I read serval threads here where people had a similar problem, but the solution was always <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

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? This both scans packages for beans to register and activates annotation. If you don't have a <context:component-scan> the @Transactional annotation will not wrapp the method in a transaction.

I have found solution of this issue by implementing ApplicationListener<ContextRefreshedEvent> and putting a self reference to the service call.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM