ablong 2009-03-17 10:02
浏览 318
已采纳

hibernate 延迟加载 数据调用

我在做一个小的项目,锻炼一下自己。请问一下我用的是struts+hibernate,其中有的team(班级)和Student多对一的关系,team对班级设置的是延迟加载,当我在页面中调用team.getStudents()的时候提示session was closed,但是我用不想把student设置为立即加载,有什么办法能使调用team.getStudents()方法时打开session?
[b]问题补充:[/b]
谢谢以上两位的回答,我现在还想问一下,我想让原来的项目保持struts+hibernate保持不变想要实现对students的延迟调用是使用OpenSessionInView 好呢还是自己做一个filter好呢,那个更方便,具体的做法是怎样的?这是我帮别人做得网站,很急,希望高手们能帮一下,谢了!
[b]问题补充:[/b]
如果使用OpenSessionInView 该引入哪些jar包?我感觉这个问题是hibernate很大的一个缺陷啊,为什么hibernate自己不做一个jar包解决呢,而使用spring的,这样很麻烦那

  • 写回答

11条回答 默认 最新

  • wanghaolovezlq 2009-03-17 13:30
    关注

    给你粘出几个类的代码,你自己看看,
    类HibernateUtil.java,用这个类来管理session和事务
    [code="java"]
    import org.hibernate.*;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.exceptions.InfrastructureException;
    import org.apache.commons.logging.*;

    import javax.naming.*;

    /**

    • Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
    • Uses a static initializer for the initial SessionFactory creation
    • and holds Session and Transactions in thread local variables. All
    • exceptions are wrapped in an unchecked InfrastructureException. *
    • @author christian@hibernate.org
      */
      public class HibernateUtil {

      private static Log log = LogFactory.getLog(HibernateUtil.class);

      private static Configuration configuration;
      private static SessionFactory sessionFactory;
      private static final ThreadLocal threadSession = new ThreadLocal();
      private static final ThreadLocal threadTransaction = new ThreadLocal();
      private static final ThreadLocal threadInterceptor = new ThreadLocal();

      // Create the initial SessionFactory from the default configuration files
      static {
      try {
      configuration = new Configuration();
      sessionFactory = configuration.configure().buildSessionFactory();
      // We could also let Hibernate bind it to JNDI:
      // configuration.configure().buildSessionFactory()
      } catch (Throwable ex) {
      // We have to catch Throwable, otherwise we will miss
      // NoClassDefFoundError and other subclasses of Error
      log.error("Building SessionFactory failed.", ex);
      throw new ExceptionInInitializerError(ex);
      }
      }

      /**

      • Returns the SessionFactory used for this static class. *
      • @return SessionFactory / public static SessionFactory getSessionFactory() { / Instead of a static variable, use JNDI: SessionFactory sessions = null; try { Context ctx = new InitialContext(); String jndiName = "java:hibernate/HibernateFactory"; sessions = (SessionFactory)ctx.lookup(jndiName); } catch (NamingException ex) { throw new InfrastructureException(ex); } return sessions; */ return sessionFactory; }

      /**

      • Returns the original Hibernate configuration. *
      • @return Configuration */ public static Configuration getConfiguration() { return configuration; }

      /**

      • Rebuild the SessionFactory with the static Configuration. * */ public static void rebuildSessionFactory() throws InfrastructureException { synchronized(sessionFactory) { try { sessionFactory = getConfiguration().buildSessionFactory(); } catch (Exception ex) { throw new InfrastructureException(ex); } } }

      /**

      • Rebuild the SessionFactory with the given Hibernate Configuration. *
      • @param cfg */ public static void rebuildSessionFactory(Configuration cfg) throws InfrastructureException { synchronized(sessionFactory) { try { sessionFactory = cfg.buildSessionFactory(); configuration = cfg; } catch (Exception ex) { throw new InfrastructureException(ex); } } }

      /**

      • Retrieves the current Session local to the thread.
      • If no Session is open, opens a new Session for the running thread. *
      • @return Session */ public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { log.debug("Opening new Session for this thread."); if (getInterceptor() != null) { log.debug("Using interceptor: " + getInterceptor().getClass()); s = getSessionFactory().openSession(getInterceptor()); } else { s = getSessionFactory().openSession(); } threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s; }

      /**

      • Closes the Session local to the thread. */ public static void closeSession() throws InfrastructureException { try { Session s = (Session) threadSession.get(); threadSession.set(null); if (s != null && s.isOpen()) { log.debug("Closing Session of this thread."); s.close(); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } }

      /**

      • Start a new database transaction. */ public static void beginTransaction() throws InfrastructureException { Transaction tx = (Transaction) threadTransaction.get(); try { if (tx == null) { log.debug("Starting new database transaction in this thread."); tx = getSession().beginTransaction(); threadTransaction.set(tx); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } }

      /**

      • Commit the database transaction. */ public static void commitTransaction() throws InfrastructureException { Transaction tx = (Transaction) threadTransaction.get(); try { if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { log.debug("Committing database transaction of this thread."); tx.commit(); } threadTransaction.set(null); } catch (HibernateException ex) { rollbackTransaction(); throw new InfrastructureException(ex); } }

      /**

      • Commit the database transaction. */ public static void rollbackTransaction() throws InfrastructureException { Transaction tx = (Transaction) threadTransaction.get(); try { threadTransaction.set(null); if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { log.debug("Tyring to rollback database transaction of this thread."); tx.rollback(); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } finally { closeSession(); } }

      /**

      • Reconnects a Hibernate Session to the current Thread. *
      • @param session The Hibernate Session to be reconnected. */ public static void reconnect(Session session) throws InfrastructureException { try { session.reconnect(); threadSession.set(session); } catch (HibernateException ex) { throw new InfrastructureException(ex); } }

      /**

      • Disconnect and return Session from current Thread. *
      • @return Session the disconnected Session
        */
        public static Session disconnectSession()
        throws InfrastructureException {

        Session session = getSession();
        try {
        threadSession.set(null);
        if (session.isConnected() && session.isOpen())
        session.disconnect();
        } catch (HibernateException ex) {
        throw new InfrastructureException(ex);
        }
        return session;
        }

      /**

      • Register a Hibernate interceptor with the current thread.
      • Every Session opened is opened with this interceptor after
      • registration. Has no effect if the current Session of the
      • thread is already open, effective on next close()/getSession(). */ public static void registerInterceptor(Interceptor interceptor) { threadInterceptor.set(interceptor); }

      private static Interceptor getInterceptor() {
      Interceptor interceptor =
      (Interceptor) threadInterceptor.get();
      return interceptor;
      }

    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用