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?
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.