Abdulla Elsayed
Abdulla Elsayed

Reputation: 23

Hibernate framework - why one session is not enough

I am now working with the Hibernate framework in Java and I need to understand why we should use one session for every process. Why don't we use one global session for the whole program?

Upvotes: 0

Views: 112

Answers (2)

zawarudo
zawarudo

Reputation: 2496

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer, create, read, and delete operations for instances of mapped entity classes.

Upvotes: 1

Rahul
Rahul

Reputation: 299

You don't need to use one session for a process but for a thread and that too at one point of time. The restriction should be on threads, not processes. In a JVM process there can be multiple threads using a database connection pool. When using a connection pool connections are reused between threads in such a way that transaction boundaries are not overlapped which is the main idea of using one session ie. connection for a thread. See Transactions and concurrency control

Upvotes: 1

Related Questions