我们在 hibernate.cfg.xml 中提供数据库凭证
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">url</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<session-factory>
<hibernate-configuration>
我们可以在此处或在类路径中的 hibernate.properties 中提供这些属性。但我希望它们来自外部文件。我在 hibernate 中找不到更改默认 hibernate.properties 文件路径的方法。
请帮忙。
[编辑] java中生成sessionFactory对象的方法
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
// Create the session factory from hibernate.cfg.xml
Configuration configuration = new Configuration();
StandardServiceRegistryBuilder serviceRegistryBuilder =
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
return configuration.buildSessionFactory(serviceRegistryBuilder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
最佳答案
以编程方式,您可以加载 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;
}
}
整个 Spring
您可以使用 PropertiesFactoryBean 从文件中读入属性并配置 LocalSessionFactoryBean:
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="hibernateProperties">
<bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">path-to-properties-file</property>
</bean>
</property>
...
</bean>
希望它有用。
关于java - 使用 hibernate.cfg.xml 时更改 hibernate.properties 文件的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041715/