【问题标题】:hibernate.cfg.xml does not find hibernate.properties filehibernate.cfg.xml 没有找到 hibernate.properties 文件
【发布时间】:2012-11-09 07:44:43
【问题描述】:
我们曾经将 hibernate.cfg.xml 和 hibernate.properties 文件放在 Java 源文件夹的同一个文件夹中。现在我将 hibernate.properties 文件移动到另一个位置。如何让 hibernate.cfg.xml 文件再次找到 hibernate.properties 文件?我收到一个错误,似乎表明它不再被发现。
【问题讨论】:
标签:
java
hibernate
hibernate.cfg.xml
【解决方案1】:
以编程方式,您可以像这样加载 XML 和属性:
public class MyHibernate {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
URL r1 = MyHibernate.class.getResource("/hibernate.cfg.xml");
Configuration c = new Configuration().configure(r1);
try {
InputStream is = MyHibernate.class.getResourceAsStream("/hibernate.properties");
Properties props = new Properties();
props.load(is);
c.addProperties(props);
} catch (Exception e) {
LOG.error("Error reading properties", e);
}
return c.buildSessionFactory();
} catch (Throwable ex) {
LOG.error("Error creating SessionFactory", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
希望有用。