What is a database session?

Session is more than just a transaction, it is an implementation of UnitOfWork pattern. In other words it holds on to the loaded objects, knows which objects has to be persisted etc:

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

To better understand relation between Session and Transaction you can take a look at this article.

A single Hibernate Session might have the same scope as a single database transaction.

This is the most common programming model used for the session-per-request implementation pattern. A single Session and a single database transaction implement the processing of a particular request event (for example, a Http request in a web application). Do never use the session-per-operation anti-pattern! (There are extremely rare exceptions when session-per-operation might be appropriate, you will not encounter these if you are just learning Hibernate.)

Another programming model is that of long Conversations, e.g. an application that implements a multi-step dialog, for example a wizard dialog, to interact with the user in several request/response cycles. One way to implement this is the session-per-request-with-detached-objects pattern. Once persistent objects are considered detached during user think-time and have to be reattached to a new Session after they have been modified.

The session-per-conversation pattern is however recommended. In this case a single Session has a bigger scope than a single database transaction and it might span several database transactions. Each request event is processed in a single database transaction, but flushing of the Session would be delayed until the end of the conversation and the last database transaction, to make the conversation atomic. The Session is held in disconnected state, with no open database connection, during user think-time. Hibernate's automatic optimistic concurrency control (with versioning) is used to provide conversation isolation.


@Dmitry has answered very nicely.

Another way to look at the session is as Instance of Database Usage. When you create a session, you have a context ready for any database interaction with support services (e.g. transaction, caching, connection etc) required therein. A transaction is an independent service used within the session.

Also the session is the first level cache used by the typical OR mapping tools like hibernate. Session acts as temporary context created upon request to facilitate a DB interaction.