GionJh
GionJh

Reputation: 2884

Persistence context lifecycle in JPA

I'm a bit of confused about persistence context and its lifecycle.
Suppose I have a simple DAO class such as the following.

public class UserDao
{
    @PersistenceContext
    private EntityManager manager;

    public User getUserById(Integer id)
    {
     return manager.find(User.class, id); 
    }

    public User getUserByName(String name)
    {
        Query q = manager.createQuery("SELECT u FROM User u WHERE u.name = ?1");
        q.setParameter(1, name);

        @SuppressWarnings("unchecked")
        List<User> list = (List<User>) q.getResultList();

        if(!list.isEmpty())
         return list.get(0);

        return null;
    }  
}  

In my understanding each invocation of method on the EntityManager is
like a transaction on its own, so a persistence context is created
and closed soon after retrieving results or actuating changes,
and the Entities that are returned are detached.

Please correct me if I'm wrong.

Now even if in one of the methods above used the EntityManager twice, two separate persistence contexts would come to play one after another, is that right ?

An invocation of EntityManager returns managed entities only if the persistence conext has not already been closed, and that happens when we are in a transaction scope.

It may seem not clear what I'm asking, but I just would like you to validate my knoledge or provide clrifications, thanks for your time and patience.

Upvotes: 0

Views: 3119

Answers (1)

Kaputnik120
Kaputnik120

Reputation: 300

The PersistenceContext lives until the EntityManager is closed. When the EntityManager is closed, depends on the scope of the EntityManager and whether it is managed by your application or an JavaEE container. See here for details: http://piotrnowicki.com/2012/11/types-of-entitymanagers-application-managed-entitymanager/

Upvotes: 1

Related Questions