• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
  • Piet Souris
  • Himai Minh

Multiple Database Connections with Hibernate 3

Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!");
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();
return s;

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

The fastest and most reliable components of any system are those that are not there. Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
    Bookmark Topic Watch Topic
  • New Topic