Hibernate session vs DB connection

I’m a little confused on the difference between Hibernate session(or JPA entity manager) to database connection.

Does is mean when I call sessionfactory.openSession a database connection is opened and held open till the session is closed?
I read in this book Java Persistence with Hibernate that Hibernate is lazy and db connection is not retrieved until SQL execution is needed .

can someone clarify me the differences?

Than you in advance

Hibernate will only acquire the JDBC connection on first database access. It will keep it open depending on various settings and usually, at least until a transaction ends, as local transactions are bound to the connection.

Thank you for answering but I don’t understand what do u mean by first database access?
If I open a transaction and all my entities are present in persistence context I don’t need to access the db but I’ve already opened transaction

what do u mean by first database access?

The first operation with the Session/EntityManager that causes SQL to be executed will obviously acquire the connection to execute the operation. Starting a transaction is a database interaction as well.

all my entities are present in persistence context

I don’t know what that means. You have to somehow get the entities into that persistence context by invoking some operations on Session/EntityManager, so that will execute SQL and thus acquire a connection.

I’ve not been clear enough I guess. Sorry for that.
Say I have an entity manager that holds some entities in the persistence context from interacting with the db (opening and closing transaction)
Time has pass on and a new query need to be executed to fetch entities. A priori I don’t know which entities are presented in persistence context and so in my code I open a new transaction and execute a find method/query on the entity manager. If me entities are already present in the persistent context (from earlier operation) do Hibernate still fetch db connection? Since I’ve opened a transaction I assume yes but not query are needed to be executed since all entities are present in first level cache. Am I right?

Depends what kind of query you are executing. EntityManager.find will look into the first level cache first, but a query will always hit the database unless you configured second level caching and query caching.

I would suggest you don’t open a transaction if this is a read only use case, as the transaction commit/rollback will acquire the connection.

2 Likes