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!
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