在Web应用中,当查询出来的对象返回给UI层之前Session已经关闭了,如果此时需要显示延迟加载的数据,将会出错。当然也可以让hibernate强行加载数据再关闭Session!但是在Hibernate层无法知道UI层是否需要这些数据~
    大家有什么使用延迟加载比较好的方式吗?欢迎讨论~

解决方案 »

  1.   

    提供一个简单的实现吧.
    下面这个工具类,Hibernate的官方reference中有提供.import net.sf.hibernate.*;
    import net.sf.hibernate.cfg.*;public class HibernateUtil {    private static Log log = LogFactory.getLog(HibernateUtil.class);    private static final SessionFactory sessionFactory;    static {
            try {
                // Create the SessionFactory
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
                log.error("Initial SessionFactory creation failed.", ex);
                throw new ExceptionInInitializerError(ex);
            }
        }    public static final ThreadLocal session = new ThreadLocal();    public static Session currentSession() throws HibernateException {
            Session s = (Session) session.get();
            // Open a new Session, if this Thread has none yet
            if (s == null) {
                s = sessionFactory.openSession();
                session.set(s);
            }
            return s;
        }    public static void closeSession() throws HibernateException {
            Session s = (Session) session.get();
            session.set(null);
            if (s != null)
                s.close();
        }
    }
      

  2.   

    然后写一个过滤器.public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
                  throws IOException,ServletException {
      try{
        chain.doFilter(request,response) 
      }finally{
        try{
           HibernateUtil.closeSession();
        }catch(Exception ex){
        }
      }
    }在所有使用Hibernate的地方,使用HibernateUtil.currentSession()得到session.