rsanheim wrote:
I have been looking over the standard HibernateUtil provided with Hibernate in Action and thinking about how to test hibernate in my app. The simplest way I can think of is to use HibernateUtil but set my own Configuration on it before it loads the SessionFactory, but you can't do that with the static block as it will always run first using some default. I could swap out config files that the static block looks for, but I'd rather drive the config from my code so I can do this from TestCase setup or decorator. Also, we are not using Spring so there is no easy IoC available that way...
Does anyone see a problem with using a lazily configured SessionFactory so as to allow a setConfig()/load of configuration resources before the factory is loaded? In production, I suppose setConfig and load would be called with the default production db in a startup servlet so the factory gets loaded when the web app starts up. In our test environment, I could do a setConfig before running tests, so we could hit HSQLDB or whatever.
Comments?
- Rob
http://www.robsanheim.com
I'm pretty sure I copied this from a book or somewhere but the lazy-initialization is how I do it.
Code:
public static Session getSession() {
Session session = (Session) threadLocalSession.get();
if (session == null) {
if (sessionFactory == null) {
Configuration cfg = new Configuration();
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
session = sessionFactory.openSession();
session.connection().setAutoCommit(false);
threadLocalSession.set(session);
}
return session;
}