What exactly is a session in hibernate?

Viewed 381

According to hibernate's official documentation, a session is "the main runtime interface between a Java application and Hibernate." I am aware the functionality of a session is to provide a physical connection between the application and database. However, my question is, what exactly is a session and how does it work behind the scene?

1 Answers

The hibernate session acts as a buffer between the application and the database. It caches objects retrieved from the database so it can provide those objects if they’re needed again without hitting the database. This is good for performance and also makes sure the java code’s view of the database is more consistent (caching means no non-repeatable reads). Flush modes can be configured or application code can flush the session if this caching gets in the way.

When the application saves changes, hibernate doesn’t send inserts and updates to the database right away, the changes are saved in the session, to be sent to the database the next time the session is flushed. Hibernate decides what order to execute them in. This allows hibernate to use jdbc batching and also reduces the scope of any database locking it has to do.

Related