Reputation: 2280
i am trying to make multiple hibernate.cfg.xml files as each will have different connection properties in them. how do i specify which cfg file i want inside of each class that uses them?
here is my session factory:
public class DatabaseUtilities {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory(String configFile) {
try {
return new AnnotationConfiguration().configure(configFile).buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
of course this throws errors right now because i dont know how to pass the parameter into the object at the top.
this is how i call the session factory from my class
Session s = DatabaseUtilities.getSessionFactory().openSession();
how can i modify this code to take the string of the .xml passed in by the class using it?
Upvotes: 0
Views: 529
Reputation: 1069
As you're encapsulating the access to the SessionFactory in a Singleton-way, you could perhaps rewrite it not to follow the Static block initialization
but Lazy initialization
:
public class DatabaseUtilities {
private static final SessionFactory sessionFactory = null;
private static SessionFactory buildSessionFactory(String configFile) {
try {
return new AnnotationConfiguration().configure(configFile).buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static synchronized SessionFactory getSessionFactory(String configFile) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(configFile);
}
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
private DatabaseUtilities() {}
}
Now you can call your utilities class this way:
DatabaseUtilities.getSessionFactory("path/to/hibernate.cfg.xml");
Upvotes: 1