Reputation: 2948
I am quite new with Hibernate and I have this newbie question in my head the clear answer to which I couldn't find anywhere online.
In my multithreaded application I want to use Hibernate for data persistence. The app by nature is event based, means that new event will spawn new thread to process incoming data. From one of online Getting Started
tutorials I implemented Hibernate Session Factory which will create single session object and will return it upon HibernateUtil.getSessionFactory().getCurrentSession()
. From same tutorial I use this factory as follows:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
/*
do smth here
*/
session.getTransaction().commit();
What I want to clarify is since there is only one session object shared across different threads will the concurrency work with this code?
For example I am not clear how it will handle situations when 1st thread started transaction, then 2nd thread started transaction, then 1st thread tries to commit transaction, which transaction will it commit? Since I am apllying HQL or Criteroins to Session object, would it know which transaction it should be applied to?
Upvotes: 1
Views: 4778
Reputation: 1058
SessionFactory - It shared single object to whole application.It is threadsafe.
Session - It will be created for every application request. It does share with any other object and It is not threadsafe.
Upvotes: 0
Reputation: 15240
No need to worry about a session being shared across multiple threads. By default the SessionFactory
will bind a Session
per thread in each of the 3 possible configurations. Here it is an extract from Hibernate 4 docs:
However, as of version 3.1, the processing behind SessionFactory.getCurrentSession() is now pluggable. To that end, a new extension interface, org.hibernate.context.spi.CurrentSessionContext, and a new configuration parameter, hibernate.current_session_context_class, have been added to allow pluggability of the scope and context of defining current sessions.
...
Out-of-the-box, Hibernate comes with three implementations of this interface:
org.hibernate.context.internal.JTASessionContext: current sessions are tracked and scoped by a JTA transaction. The processing here is exactly the same as in the older JTA-only approach. See the Javadocs for details.
org.hibernate.context.internal.ThreadLocalSessionContext:current sessions are tracked by thread of execution. See the Javadocs for details.
org.hibernate.context.internal.ManagedSessionContext: current sessions are tracked by thread of execution. However, you are responsible to bind and unbind a Session instance with static methods on this class: it does not open, flush, or close a Session.
Upvotes: 2