Using injected EntityManager in class hierarchies

Posted by Emre Sahin on Stack Overflow See other posts from Stack Overflow or by Emre Sahin
Published on 2010-03-20T19:10:55Z Indexed on 2010/03/20 19:11 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

The following code works:

@Stateless
@LocalBean
public class MyClass 
{
       @PersistenceContext(name = "MyPU")
       EntityManager em;


       public void myBusinessMethod(MyEntity e)
       {
          em.persist(e);
       }
 }

But the following hierarchy gives a TransactionRequiredException in Glassfish 3.0 (and standard JPA annotations with EclipseLink.) at the line of persist.

 @Stateless
 @LocalBean
public class MyClass extends MyBaseClass
{
       public void myBusinessMethod(MyEntity e)
       {
          super.update(e);
       }
 }



public abstract class MyBaseClass
{
       @PersistenceContext(name = "MyPU")
       EntityManager em;

       public void update(Object e)
       {
          em.persist(e);
       }
 }   

For my EJB's I collected common code in an abstract class for cleaner code. (update also saves who did the operation and when, all my entities implement an interface.)

This problem is not fatal, I can simply copy update and sister methods to subclasses but I would like to keep all of them together in a single place.

I didn't try but this may be because my base class is abstract, but I would like to learn a proper method for such a (IMHO common) use case.

© Stack Overflow or respective owner

Related posts about j2ee

Related posts about java