Hibernate:用另一个文件覆盖xml配置文件

时间:2011-05-24 21:48:30

标签: java unit-testing hibernate

我有一个由源代码和测试类组成的源代码树。当我运行测试时,我想在运行代码时使用<property name="hbm2ddl.auto">create</property>我想使用validate值而不是create。 我想使用两个配置文件,一个包含所有属性,包含hbm2ddl.auto设置为validate,另一个配置为hbm2ddl.auto设置为create。我希望以下代码允许我从测试中读取基本文件并覆盖唯一的hbm2ddl.auto属性,但它不起作用(hbm2ddl.auto的值仍然是从hibernate.cfg读取的值)。 xml。

Configuration configuration = new Configuration();
configuration = configuration.
    configure("hibernate.cfg.xml").
    addResource("hibernate-test.cfg.xml");

如何在不复制整个配置文件的情况下为属性设置两个不同的值?

2 个答案:

答案 0 :(得分:5)

在我看来,当你只有几个值要覆盖时,一个简单的方法就是像往常一样加载xml配置,然后以编程方式调用setProperty,如下所示:

Configuration configuration = new Configuration();
configuration = configuration.configure("hibernate.cfg.xml");
configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");

hbm.xml文件不允许在我尝试的情况下覆盖addResource(...)的值,只会添加值而不会覆盖

答案 1 :(得分:0)

我尝试以编程方式加载另一个配置时遇到了这个问题。我使用的解决方法是使用另一个hibernate.properties文件(而不是xml配置)。您可以在此属性文件中设置备用hibm2ddl值,并使用以下代码加载它:

        Properties props = new Properties();
        props.load(new FileInputStream(propFile));
        configuration = new Configuration().setProperties(props);

尝试看看这是否适合你。

Imp:不要调用configuration.configure()。

相关问题