Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does hibernate sessionfactory manage session?

I have just got the relationship between Hibernate Session and Connection. But now, I get another question: how does hibernate sessionfactory manage session? In the following code segment: save() method of a DAO class:

Session session = sessionFactory.openSession();
   Transaction tx=null;
   tx=session.beginTransaction(); 
   session.save(transientInstance);
   session.flush();
   tx.commit();

When we call sessionFactory.openSession() , it will create a new session attached to the current thread (through the ThreadLocal), this session is also attached to a JDBC connection, But, as you can see, we don't need to close the session (session.close()), neither the connection. So, what is the lifecycle of a Hibernate session, in what circumstances it will be closed? automatically?

like image 240
Yves Messi Avatar asked Mar 25 '13 11:03

Yves Messi


People also ask

How does SessionFactory work in hibernate?

The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.

What is session management in hibernate?

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.

What is SessionFactory session and transaction in hibernate?

Most importantly, the SessionFactory in Hibernate is responsible for the creation of Session objects. The Hibernate Session provides methods such as save, delete and update, all of which are used to perform CRUD-based operations on the database to which the SessionFactory connects.


1 Answers

I recommend the getCurrentSession method because only with this method you have the possibility to be sure that the session will be closed from hibernate

Configuration J2EE Current Session.

If you use the openSession method, you must close the sessions by yourself. After i begin to work with hibernate i thought it does'n matter which method I use because all session will be closed automatically... i was wrong. I had discovered with the SessionStatistics from hibernate SessionStatistics that the open session was already opened and never closed.

After i changed all calls to getCurrentSession and impl. the Session-per-request pattern opened session will be closed after work.

Transactions Basics.

like image 68
Zelldon Avatar answered Oct 08 '22 23:10

Zelldon