Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

jpa

When I call:

entityManager.flush()

I get the exception mentioned in the title.

I am using Hibernate JPA.

like image 748
kcheng Avatar asked Nov 26 '09 06:11

kcheng


3 Answers

After encountering this problem myself and spending a few hours trying to get it resolved I finally found a reason for it: Spring has a bug and can't maintain transactions with @Transactional annotation if the same class has @Service annotation for the means of autowiring.

Once the @Service annotation was removed from the service class in question, and an appropriate bean was declared in the XML config:

<bean id="myService" class="com.example.myapp.service.MyServiceImpl" /> 

the problem is gone.

Check this JIRA bug for more details.

like image 168
Roman Avatar answered Oct 06 '22 21:10

Roman


Ensure that you have an active transaction when this statement executes. If you are using JPA use EntityManager.getTransaction().begin(). This is assuming that you are using JPA outside a JTA transaction scope.

If you are running the application inside a container with JTA support you can also use JTA UserTransaction to manage transactions.

like image 42
Chandra Sekar Avatar answered Oct 06 '22 21:10

Chandra Sekar


My Problem was to do with the way that I setup the <tx:annotation-driven/> Element in my context definition -

Originally I had load time weaving enabled (not knownley) that read <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/> and by simply removing the 2nd attribute - everything worked (took 2 hours of head banging though). I believe the 2nd element relates to the @Configurable sterotype but can let other (smarter) people explain the difference & why one would work & the other does does not.. Hope this helps...

working definition= <tx:annotation-driven transaction-manager="transactionManager"/>

like image 39
Mannie Avatar answered Oct 06 '22 23:10

Mannie