I have a helper class that uses the ThreadLocal Session pattern to generate the SessionFactory. However, I need to dynamically configure the mySQL database that hibernate connects to so the SessionFactory in my helper class isn't declared static. Instead I instantiate a HibernateHelper object in my main app, passing the database name to connect to. I'm curious if this is an acceptable way to do things, are there any negative side effects, or if there is a better way to dynamically configure a SessionFactory at runtime. Here's my helper class:
thanks in advance!
public class HibernateHelper
{
public HibernateHelper(String dbNameIn) // database to connect to
{
connectURL = connectURL + dbNameIn;
sessionFactory = new Configuration()
.setProperty("hibernate.connection.url", connectURL)
.configure()
.buildSessionFactory();
}
public Session getSession()
{
Session session = (Session) HibernateHelper.session.get();
if (session == null)
{
session = sessionFactory.openSession();
HibernateHelper.session.set(session);
}
return session;
}
private String connectURL = "jdbc:mysql://localhost/";
private static final ThreadLocal session = new ThreadLocal();
private static final ThreadLocal transaction = new ThreadLocal();
// SessionFactory would normally be static but not here since the configuration
// is determined at runtime
private final SessionFactory sessionFactory;
}
|