I have a simple class which starts 3 threads and saves a new object in each thread. But I am getting exception which i cannot understand. Can anyone help me understand why the e
A Session is actually a Unit of Work which should be bound to the current executing Thread. A unit of work group multiple DML operations inside a single transaction which can succeed only if all operations succeed. So a session is atomic, and atomicity implies a single operating thread.
The Session is also the 1st Level Cache, so in the current Session you will always get the same Entity object reference, no matter how many times you call session.get() or session.load(). If a Session were thread-safe than during flush time you might execute other transaction intermediary changes. So a Session must be isolated from other executing Session, and isolation implies a single operating thread.
So, a Session is not meant to be thread-safe to preserve the atomicity and isolation requirements.
if its helpful for anybody else, for me this meant "you did a mockito spy(database)" in a previous unit test, which somehow hosed hibernate. Go figure.
Session object in Hibernate is not thread safe, you should not use the same session in different threads, unless you synchornize access to Session object.
Call .openSession()
instead of .getCurrentSession()
after getSessionFactory()
.
The sessionFactory
object is thread-safe but each Session
object should be single-threaded.