Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Sessions and Transactions with Threads

I'm working on a project that uses Hibernate3 and JDBC to connect/interact with our database (MSSQL 2008)

Currently we create our session factory in our main class then begin our transaction, then we start a new thread and that thread creates connections and what not. I'll see if I can illustrate this with some pseudo code...

public static main(String[] args){
    for(...){
        SessionFactory sf = new SessionFactory();
        sf.getCurrentSession.beginTransaction();
        CreateNewThreadedObject.run();
        sf.getCurrentSession.getTransaction.commit();
    }
}

My question is, is this safe? I know that sessions are not thread safe, but I'm not really using the session in the thread. If anything I'm using the Transaction. Would passing the sessionfactory to the threaded object be better? Any advice is appreciated!

like image 794
Shaded Avatar asked Feb 25 '23 09:02

Shaded


2 Answers

It's very important that you understand Hibernate Sessions and thread association, best explained here:

http://community.jboss.org/wiki/Sessionsandtransactions

If you're working with a web app, I highly recommend the Open Session in View pattern:

https://community.jboss.org/wiki/OpenSessionInView

like image 101
kvista Avatar answered Mar 08 '23 10:03

kvista


You can initialize a singleton SessionFactory. That is actually recommended.

Then, each thread should create a Session using the session factory and perform transaction(s).

This is actually a very common pattern used in web applications. The Open Session in View pattern that @kvista mentions, is basically a servlet filter that creates a session, begins a transaction, delegates to whatever continues the request processing and in the end commits or rolls back the transaction. And since each request is processed by a different thread in a servlet container, you can see how close the two cases are.

In your case, it wouldn't be unreasonable to execute many transactions in each thread. That is actually the basic idea of executing batch processes in a multi-threaded (ideally JTA) environment. One thing that you should note however, is that the session is actually a persistence context that acts as a cache and you should probably clear it from time to time to avoid memory leaks.

like image 30
dkateros Avatar answered Mar 08 '23 10:03

dkateros