The main function of a Hibernate session is to open a database connection, and offer read and update operations for instances. Each instance object associated with the session will keep alive until the session is closed or the object is deleted.
As the session is a light weight and a non thread safe object, session objects should not be kept for a long time. A session is opened by a SessionFactory, and is closed when all work is complete. In Hibernate, instances have three states:
- transient – not associated with any session
- persistent – associated with a single session
- detached – previously persistent state, now not associated with any session. Detached objects can be passed across layers all the way up to the presentation layer (DTO still a better practice). The detached objects can be reattached to another session later.
The diagram shows how the states of the instance change.
A typical transaction will look like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/* Configuration configuration = new Configuration(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); */ Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // DB query or update tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw e; } finally { session.close(); } |
If the Session throws an exception, the transaction must be rolled back and the session discarded. Make sure don’t leave the session not closed over long time. Otherwise, if there are lots of sessions created, but never closed , you will see the memory usage will grow up very fast, and you may see Out Of Memory error in the future.