Does JPA EntityManager hold DB connection when created

According to this book :

Creating an EntityManager starts its persistence context. Hibernate won’t access
the database until necessary; the EntityManager doesn’t obtain a JDBC Connection
from the pool until SQL statements have to be executed. You can create and close an EntityManager without hitting the database

My super simple program is this:

 EntityManager outerEm = emf.createEntityManager();
 logger.info("Connection is closed [after create em]  "+outerEm.unwrap(Session.class).doReturningWork(Connection::isClosed));

and surprisingly the log says : - Connection is closed [after create em] false

Why entity manager holds db connection if it has no SQL statement to execute?

By calling doReturningWork you essentially tell Hibernate to acquire a connection if it doesn’t have one yet.

2 Likes

I see…silly me :slight_smile:
Thank you