• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiple Database Connections with Hibernate 3

 
Adrian Enns
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using Hibernate 3.0 with MySql 4.1.

I have created one session-factory in the hibernate.cfg.xml to connect to my database and my code is working. How does my code need to change if I add another session-factory/database connection? I currently am using a class called HibernateUtil to access the Session, the code is below. How do things work if I have several session-factories defined in the hibernate.cfg.xml file?

public class HibernateUtil
{
private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.out.println("ERROR INITIALIZING!");
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}

public static void closeSession()
{
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic