如何从不同的位置加载hibernate.cfg.xml

问题描述 投票:11回答:4

我正在使用hibernate创建一个jar。我遇到过需要经常更改设置(url)的情况,所以我想像这样加载hibernate.cfg.xml

SessionFactory sessionFactory = new Configuration()
                                     .configure("D:\\fax\\hibernate.cfg.xml")
                                     .buildSessionFactory();

但是然后运行项目我得到了这个例外

org.hibernate.HibernateException: D:\fax\hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)
    at hibernate.LabOrderHelper.getDatabaseSesssion(LabOrderHelper.java:55)
    at hibernate.Test.main(Test.java:42)

如何从类路径的不同位置加载hibernate.cfg.xml

java xml hibernate
4个回答
20
投票

public Configuration configure(File configFile)类中有一种方法Configuration

尝试以下,它应该工作肯定:)

File f = new File("D:\\fax\\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(f).buildSessionFactory();

不同的是你使用了一个方法configure(String resource),它在类路径中期望一个资源,但是当configure(File configFile)期待一个File时,你可以传递它。


2
投票

我需要经常更改sql设置(url)

我有同样的要求。对于仅切换数据库连接属性,接受的答案中建议的方法虽然有效,但却是一种钝器。

加载完全不同的配置文件只是为了更改一些连接属性?现在,两者中常见的所有其他属性都是重复的,每次进行更改时,都需要在两个位置进行更改。

更好的方法是在默认的hibernate.cfg.xml中放置不需要在环境之间更改的所有公共属性,像往常一样从中构建Configuration,并使用.addProperties()方法在顶部添加特定于环境的属性,这种情况下连接url。您可以从任何您喜欢的地方加载这些额外的属性。

public SessionFactory buildSessionFactory() {
   return getConfiguration().buildSessionFactory();
}

private Configuration getConfiguration() {
   Configuration config = new Configuration.configure(); // load the base config from the default hibernate.cfg.xml
   return config.addProperties(getConnectionProperties()); // add your custom connection props for this environment on top
}

private Properties getConnectionProperties() {
  Properties connectionProps = new Properties();
  connectionProps.put("hibernate.connection.url", getConnectionUrl()); 
  // possibly add other props like hibernate.connection.username, hibernate.connection.password
  return connectionProps;
}

private String getConnectionUrl() {
  // get your connection URL from wherever you like
}

1
投票

Hibernate XML配置文件“hibernate.cfg.xml”始终放在项目类路径的根目录下,位于任何包之外。如果将此配置文件放在其他目录中,则可能会遇到以下错误:

Initial SessionFactory creation failed.org.hibernate.HibernateException: 
/hibernate.cfg.xml not found

要让Hibernate在其他目录中查找“hibernate.cfg.xml”文件,可以通过将“hibernate.cfg.xml”文件路径作为参数传递给configure()方法来修改默认的Hibernate的SessionFactory类:

SessionFactory sessionFactory = new Configuration()
            .configure("/com/example/persistence/hibernate.cfg.xml")
            .buildSessionFactory();

            return sessionFactory;

HibernateUtil.java中的完整示例,从目录“/ com / example / persistence /”加载“hibernate.cfg.xml”。

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // load from different directory
            SessionFactory sessionFactory = new Configuration().configure(
                    "/com/example/persistence/hibernate.cfg.xml")
                    .buildSessionFactory();

            return sessionFactory;

        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            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();
    }

}

1
投票

补充接受的答案,您可以使用带有hibernateConfig File参数的configure(File configFile)方法从不同的目录(不一定是类路径)加载hibernate.cfg.xml。 (注意,我正在使用hibernate 4.3.7)

优点是,如果您无法访问war文件,但可以访问其他目录中的hibernate文件,比如维护。

像这样:


String hibernatePropsFilePath = "/etc/configs/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);

Configuration configuration = new Configuration(); 
configuration.configure(hibernatePropsFile);

StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

© www.soinside.com 2019 - 2024. All rights reserved.