会话在Hibernate 4.3上关闭

时间:2016-02-14 10:26:30

标签: java hibernate session

我正在使用HIbernate 4.3而且我遇到了会话问题。我试图在数据库上做一些操作但是没有正常工作。我收到会话关闭的消息。

我的HibernateUtil类创建会话工厂:

public class HibernateUtil
{
   private static SessionFactory sessionFactory = buildSessionFactory(); 
   private static SessionFactory buildSessionFactory()
   {
      try
      {
         if (sessionFactory == null)
         {
            Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
         }
         return sessionFactory;
      } catch (Throwable ex)
      {
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }

   public static SessionFactory getSessionFactory()
   {
      return sessionFactory;
   }

   public static void shutdown()
   {
      getSessionFactory().close();
   }
}

我的hibernate.cfg.xml:

<hibernate-configuration>  
    <session-factory>  
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/db?autoReconnect=true</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">root</property> 

        <!-- Use the C3P0 connection pool. -->  
        <property name="c3p0.min_size">3</property>  
        <property name="c3p0.max_size">10</property>  
        <property name="c3p0.timeout">1800</property>  

        <!-- Disable second-level cache. -->  
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>  
        <property name="cache.use_query_cache">false</property>  
        <property name="cache.use_minimal_puts">false</property>  
        <property name="max_fetch_depth">3</property>  

        <!-- Print SQL to stdout. -->  
        <property name="show_sql">true</property>  
        <property name="format_sql">true</property>  

        <!-- Drop and then re-create schema on SessionFactory build, for testing. -->  
        <property name="hbm2ddl.auto">create</property>  

        <!-- Bind the getCurrentSession() method to the thread. -->  
        <property name="current_session_context_class">thread</property>  

        <mapping class="model.User"/>
        <mapping class="model.Point"/>
        <mapping class="model.Layer"/>
        <mapping class="model.AddressDatabase"/>

    </session-factory>  

</hibernate-configuration>

我在Web.xml上启动的HibernateListener:

public class HibernateListener implements ServletContextListener {  
    public void contextInitialized(ServletContextEvent event) {  
        HibernateUtil.getSessionFactory();       
    }  
    public void contextDestroyed(ServletContextEvent event) {  
        HibernateUtil.getSessionFactory().close();
    }  
}

我的Hibernate DAOFactory:

public class HibernateDAOFactory extends DAOFactory {  
    public UserDao getUserDao() {  
        return (UserDao)instantiateDAO(UserDaoImpl.class);  
    }  

    private GenericHibernateDao instantiateDAO(Class daoClass) {  
        try {  
            GenericHibernateDao dao = (GenericHibernateDao)daoClass.newInstance();  
            dao.setSession(getCurrentSession());  
            return dao;  
        } catch (Exception ex) {  
            throw new RuntimeException("Can not instantiate DAO: " + daoClass, ex);  
        }  
    }  

    // You could override this if you don't want HibernateUtil for lookup  
    protected Session getCurrentSession() {  
        return HibernateUtil.getSessionFactory().getCurrentSession();  
    }      
}

我的HibernateDAO Factory,实例化DAO:

public class HibernateDAOFactory extends DAOFactory {  
     public UserDao getUserDao() {  
        return (UserDao)instantiateDAO(UserDaoImpl.class);  
    }  
    private GenericHibernateDao instantiateDAO(Class daoClass) {  
        try {  
            GenericHibernateDao dao = (GenericHibernateDao)daoClass.newInstance();  
            dao.setSession(getCurrentSession());t
            return dao;  
        } catch (Exception ex) {  
            throw new RuntimeException("Can not instantiate DAO: " + daoClass, ex);  
        }  
    }  
    protected Session getCurrentSession() {  
        return HibernateUtil.getSessionFactory().getCurrentSession();  
    }  

}  

GenericDAO的相关部分:

public abstract class GenericHibernateDao<T, ID extends Serializable> implements GenericDao<T, ID> {

    private Class<T> persistentClass;
    private Session session;

    @SuppressWarnings("unchecked")
    public GenericHibernateDao() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    public void setSession(Session s) {
        this.session = s;
    }

    protected Session getSession() {
        if (session == null)
            session = HibernateUtil.getSessionFactory().getCurrentSession();
        return session;
    }
    public T create(T entity) {
        getSession().save(entity);
        return entity;
    }
...

当我在数据库上执行操作序列时,我得到了错误..下面的代码是一个servlet,并显示我如何实例化我的DAO并尝试运行一些操作:

DAOFactory factory = DAOFactory.instance(DAOFactory.HIBERNATE);
userDao = factory.getUserDao();

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction;

User user = new User();
user.setEmail("xxx@gmail.com");
user.setName("xxx");
user = userDao.create(user);
tx.commit(); <-- WORKS FINE

session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction;
User user2 = userDao.findByEmail("xxx@gmail.com"); <-- HERE HAPPENS THE ERROR.

我遵循了这些教程:

https://developer.jboss.org/wiki/SessionsAndTransactions https://community.jboss.org/wiki/GenericDataAccessObjects

我尝试使用OpenSesssion而不是getCurrentSession但是我在数据库的第一个操作上遇到了这个错误: org.hibernate.HibernateException:如果没有活动事务,则save无效

当我使用另一个时,我得到了Sesssion关闭的例外情况!

任何帮助将不胜感激。 此致

0 个答案:

没有答案