在这种情况下,ThreadLocal变量有什么好处?我知道ThreadLocal变量用于保证每个线程都拥有它自己的ThreadLocal对象实例,在这种情况下我将为每个用户设置一个Session,但是Hibernate应该保证这个吗?
这是我的代码:
public class HibernateUtil {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
private static StandardServiceRegistryBuilder registryBuilder;
private static final ThreadLocal SESSION = new ThreadLocal();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration().configure();
registryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
return configuration.buildSessionFactory(registryBuilder.build());
} catch(Throwable e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
public static Session getSession() {
Session session = (Session) HibernateUtil.SESSION.get();
if(session == null) {
session = SESSION_FACTORY.openSession();
HibernateUtil.SESSION.set(session);
}
return session;
}
public static void begin() {
getSession().beginTransaction();
}
public static void commit() {
getSession().getTransaction().commit();
}
public static void rollback() {
try {
getSession().getTransaction().rollback();
} catch(HibernateException e) {
System.out.println("Cannot rollback: " + e);
}
try {
getSession().close();
} catch(HibernateException e) {
System.out.println("Cannot close: " + e);
}
HibernateUtil.SESSION.set(null);
}
public static void closeSession() {
getSession().close();
HibernateUtil.SESSION.set(null);
}
}