Monday, March 3, 2014

Resolved: Entity Manager cannot persist entities in database

Removed
I was developing a DAO layer using JPA specification (with JTA transaction managed by  Spring). When I tried to insert a new entity. I was using a shared entity manager and managing my transaction like this.

@PersistenceContext
private EntityManager entityManager;


entityManager.getTransaction().begin();

.....
entityManager.getTransaction().commit(); 

Once tested, I had this error:
 java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:220) [spring-orm-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at $Proxy82.getTransaction(Unknown Source)

So I should use Spring Transactions. I had thus added @Transaction annotation to my method, and removed the getTransaction..  I also added flush in order to "commit" the work.

entityManager.persist(item);
entityManager.flush(); 

But it didn't work and I have this error in  my log.
entitymanager persist no transaction is in progress

So I think my @Transaction annotations are not taken into consideration and thus transactions are not initialized.
So in order to solve this problem I have added this line in my applicationContext
< tx:annotation-driven/>

(as I am using jndi entitymanagerfactory lookup, I have this :
<tx:jta-transaction-manager/>)

The problem is so resolved :)

2 comments :

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

Articles les plus consultés