线程
使Session对象符合使用原则,一个线程只能有一个Session,配置如下:
1、首先在Hibernate的配置文件hibernate.cfg.xml,绑定线程
<property name="hibernate.current_session_context_class">thread</property>
2、线程工具类
public class HibernateUtils {
static Configuration cfg;
static SessionFactory factory = null;
static {
try {
cfg = new Configuration();
cfg.configure();
factory = cfg.buildSessionFactory();
} catch (ExceptionInInitializerError e) {
throw new ExceptionInInitializerError("初始化SessionFactory失败,请检查配置文件");
}
}
public static Session openSession() {
return factory.openSession();// 每次使用该方法都会返回一个新的session,不合理
}
public static Session getCurrentSession() {
return factory.getCurrentSession();// 每次使用该方法从当前线程上获取一个session,只有配置了session和线程绑定之后才能使用此方法,否则返回null
}
}
当我们把session和线程绑定之后,hibernate就会在提交或者回滚事务之后,自动帮我们关闭session。