因为SessionFactory是一个重量级的类,在一个应用中咱们须要作成单例的,我选择的作法是: `java
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; final public class Utils { private static SessionFactory sessionFactory=null; static{ //建立SessionFactory会话工厂 sessionFactory=new Configuration().configure().buildSessionFactory(); } private Utils(){ } public static SessionFactory geSessionFactory(){ return sessionFactory; } } `
这样就能够在须要的地方直接调用web
SessionFactory factory=Utils.geSessionFactory(); Session s1=factory.openSession(); Session s3=factory.getCurrentSession();
openSession()是打开一个Session,所以每次获得的Session都不同session
getCurrentSession()是获得当前线程的一个Session,在一个thread中使用该方法获得的Session都是同一个Session 可是在使用getCurrentSession()前须要在hibernate.cfg.xml中作以下配置:ui
<!-- java程序 --> <property name="current_session_context_class">thread</property> <!-- web程序 --> <property name="current_session_context_class">jta</property>
不然会报以下错误: No CurrentSessionContext configured!
在使用getCurrentSession()获得的session作查询操做(load())时须要使用事务,不然 会报以下错误:hibernate
Exception in thread "main" org.hibernate.HibernateException: load is not valid without active transaction
并且这个session是自动关闭的线程
使用load()查询时,若是查询不到,则会返回null, load()使用一种代理机制,若是不使用查询获得的对象,则不会执行SQL语句,只有使用对象时才会执行SQL语句 【懒加载】 get()查询,若是查询不到,则会抛出异常,且在查询时就执行SQL语句,无论查询的结果会不会使用