neo
neo

Reputation: 2471

How does Java EE EntityManager manage DB Connection

Suppose I have an EntityManager object em, and I have the following pseudo code:

@PersistenceContext(unitName = "myPU")
private EntityManager em;

public void runQuery()
{
    for(int i=0; i<100; i++)
    {   Query q = em.createNativeQuery(someQuery);
        List list = q.getResultList();
        //process result
        ...
        ...
    } 
}

How does the entityManager manage the underlying database connection? will there be just 1 connection session or 100 sessions for above code?

The reason I am asking is that for each connection session, I need to create a temp table before running the query. what I want to do is something like this:

    for(int i=0; i<100; i++)
    {   //first check if temp table does not exist
         createTemptTable;
       // then run the query
        Query q = em.createNativeQuery(someQuery);
        List list = q.getResultList();
        //process result
        ...
        ...
    } 

But how can I be sure it will be in the same session for creating the table and run the query?

Upvotes: 1

Views: 3786

Answers (2)

James
James

Reputation: 18389

In Java EE, in a SessionBean the persistence context is managed by the Java EE container. The injected EntityManager will normally be a proxy that holds the real JPA EntityManager. Across every JTA transaction boundary the proxy will release its JPA EntityManager and acquire a new one (or at least clear() it). Outside of a transaction, the container may acquire a new EntityManager for each operation, or may hold a single one (this is not well defined in the spec, but assume it is a new one for each request).

A JPA EntityManager that is JTA managed will use the same JDBC/database connection for the duration of a JTA transaction. So as long as your method is in a JTA transaction, your code will have the same connection. Normally SessionBean methods are transactional by default, so each method should be in its own transaction, unless you have configure it differently.

See, http://en.wikibooks.org/wiki/Java_Persistence/Runtime#Java_Enterprise_Edition

Upvotes: 1

Bogdan
Bogdan

Reputation: 944

The injected EntityManager has one connection to the DB which is taken from the connection pool managed by the container. So all your queries in the above code will run on the same connection to the database.

Upvotes: 1

Related Questions