我正在尝试制作多个hibernate.cfg.xml文件,因为每个文件都有不同的连接属性。如何在每个使用它们的类中指定我想要的cfg文件?
这是我的会议工厂:
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();
}
}
当然这会引发错误,因为我不知道如何将参数传递到顶部的对象。
这就是我从班级中调用会话工厂的方法
Session s = DatabaseUtilities.getSessionFactory().openSession();
如何修改此代码以获取类使用它传入的.xml字符串?
答案 0 :(得分:1)
当您以Singleton方式封装对SessionFactory的访问时,您可能会重写它而不是遵循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() {}
}
现在您可以这样调用您的实用程序类:
DatabaseUtilities.getSessionFactory("path/to/hibernate.cfg.xml");