hibernate sessionfactory as a global jndi resource

泄露秘密 提交于 2019-12-23 23:23:21

问题


I have a multiple contexts running in one tomcat instance each context need access to the same database.

I am running into problems with cashing because each context has its own instance of hibernate and ehcache at the moment.

This seems wrong they should only be one instance of hibernate and ehcache , this would also have better performance.

I would like to make a single instance of hibernate session factory available to all contexts, I think this can be done using a global JNDI resource in tomcat.

Is this a good way to solve this problem?

Also if anybody can provide any good resources for learning how to do this it would be much appreciated.

Update: I have managed to bind session factory to a global JNDI but a ConcurrentModificationException appears in the log during startup of tomcat.

...
INFO: schema update complete
Jan 11, 2012 2:03:19 PM org.hibernate.cache.UpdateTimestampsCache <init>
INFO: starting update timestamps cache at region: org.hibernate.cache.UpdateTimestampsCache
Jan 11, 2012 2:03:19 PM org.hibernate.cache.StandardQueryCache <init>
INFO: starting query cache at region: org.hibernate.cache.StandardQueryCache
Constructed session factory ok sf=org.hibernate.impl.SessionFactoryImpl@430e0ad7
Jan 11, 2012 2:03:19 PM org.apache.catalina.mbeans.GlobalResourcesLifecycleListener createMBeans
SEVERE: RuntimeException java.util.ConcurrentModificationException
Jan 11, 2012 2:03:19 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jan 11, 2012 2:03:19 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.23
...

回答1:


I have solved the problem by using a LifecycleListener to create a singleton instance of session factory on start up.

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactorys implements LifecycleListener  {

    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Override
    public void lifecycleEvent(LifecycleEvent arg0) {
        if (Lifecycle.AFTER_START_EVENT==arg0.getType()) {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        }
        if (Lifecycle.BEFORE_STOP_EVENT==arg0.getType()) {  
            sessionFactory.close();
        }
    }

}


来源:https://stackoverflow.com/questions/8818198/hibernate-sessionfactory-as-a-global-jndi-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!