Tuesday, November 25, 2008

Solve IllegalStateException: Illegal to call this method from injected, managed EntityManager

Problem
If we injected an EntityManager into our SessionBean and call the entityManager.getTransaction().begin() method then
IllegalStateException: Illegal to call this method from injected, managed EntityManager
exception is threw.

Java Enterprise version: JEE5
Used server: JBOSS 5.0.0.RC1
EJB version: EJB3


Why did this problem occur?
We wanted to use User-managed transaction, but this is not supported this way.

Solution
To solve this problem, we should use UserTransaction. To do this, inject a javax.ejb.SessionContext instance as Resource:
@Resource
SessionContext sc;


After this we can get an UserTransaction instrance in our method this way:
public void someMethod() {
UserTransaction ut = scgetUserTransaction();
ut.begin();
//We have an active transaction, we can access database use EntityManager intance.
ut.commit();
}

I hope it will be useful.

1 comment:

Dr. V said...

Thankyou very much!