0

Can someone explain the lifecycle of an injected EntityManager in a stateless bean? If a stateless bean has an injected EntityManager associated with a specific PersistenceContext, what happens to that association the second time the bean is used?

For example, I have the following:

@Stateless
public class TimeStepsBean
{       
    @PersistenceContext(unitName="DynamicDB")
    private EntityManager em;       

    public List<TimeStep> timeSteps = new ArrayList<TimeStep>();

    private void init()
    {
        if (timeSteps.isEmpty())
        {
            TypedQuery<TimeStep> query = em.createQuery("SELECT t FROM TimeStep t", TimeStep.class);
            timeSteps = query.getResultList();. 
        }
    }

    public void refreshSteps() 
    {
        init(); 
        em.flush(); 
        em.refresh(timeSteps.get(0));               
    }
}

When refreshSteps is called the second time the bean is used (a second transaction), I get a "java.lang.IllegalArgumentException: Entity not managed". The entityManager was injected, so I am assuming that it is always part of the current persistence context. Is that true?

Adding em.merge(timeSteps.get(0)) before the refresh still generates the same exception.

  • The container will inject a proxy EntityManager. If you are not within a transaction, this proxy will likely obtain a new EntityManager for each call, so that em.find(x.class) will never be managed when you check on the next call. – Chris May 09 '16 at 20:53
  • Take a look at this, it can help you: http://stackoverflow.com/questions/2070073/entitymanager-refresh-problem. – JMSilla May 10 '16 at 05:32
  • Are you staying that if a new transaction is starting, a new entity manager is generated for the proxy, and that entity manager is used throughout the transaction? – RunningCrazy28 May 10 '16 at 12:57

1 Answers1

0

Your timeSteps is a state. Your class is annotated as stateless. It's a misuse of the framework.

win_wave
  • 1,398
  • 9
  • 9