简体   繁体   中英

Reusing Hibernate SessionFactory

I've got a couple of class instance variables: userSF which is a SessionFactory and userCfg which is a Configuration set up to use user.cfg.xml . When I have someone log into my application their database login information is grabbed from a file the following happens:

userCfg.setProperty("hibernate.connection.username", username);
userCfg.setProperty("hibernate.connection.password", password);
userSF = userCfg.buildSessionFactory();

When the user logs out of the application it closes the session factory. then when another user tries to log in that same code is called with username and password changing based on who is logging in. The problem is that the second time it's called I'm getting an exception:

org.hibernate.HibernateException: HHH000469: The ClassLoaderService can not be reused. This instance was stopped already.

Is there a way to reuse the SessionFactory variable for multiple logins?

You should not create a SessionFactory for each logged in user / configuration. It is a very costly component and should target the Singleton pattern. Use a single instance per context within your application.

If you have multiple configurations you can cache multiple instances in application scope. Depending on your application this maybe a static Singleton class using a Map<MyUserPasswordKey, SessionFactory> or in an JAVA-EE container a @ApplicationScoped EJB or JSF-Bean.

In case a context based on a user-password key will lead to too many SessionFactory instances you maybe should change your application to either manage them in permission groups or restrict your functionality within your data access or service layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM