Thanks Mark. I just googled 'ThreadLocal' and I think I learnd something from it.. However, I still don't quite understand it --- It seems every client is using the "same" session instance but anything related to the client is held "within" its own "thread" ? Does this sound correct ? More importantly, if one client calls the "close()" method, does it mean it only close that local
thread and does NOT close the session for other clients ? Again, here is the code from the book --
public class DAO {
private static final ThreadLocal session = new ThreadLocal();
private static final SEssionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
public static Session getSession() {
Session session = (Session)DAO.session.get();
if(session==null) { session = sessionFactory.openSession(); DAO.session.set(session);
} return session;
}
public static void close() { getSession().close(); DAO.session.set(null);
}
Another question is -- Doesn't "DAO.session.set(null)" kill other clients' session ??!!
One more ting I can't understand is -- In its UserDAo class
public class UserDAO extends DAO {
public User get(
String name) {
try {
begin();
... some query code...;
return user;
} catch(HibernateException e) {rollback(); ..}
}
Question -- WOULDN"T it be nice if we ALWAYS add
finally { close();} in each method to close the session ? Can't understand why the book chooses to close the session from client side instead inside each DAO's method ?