开发者

Hibernate: overriding xml config file with another file

I have a source tree composed of source and test classes. When I run the tests, I'd like to use <property name="hbm2ddl.auto">create</property> while when running the code I'd like to use a validate value instead of create. I thought to use two config files, one with all the properties and containing hbm2ddl.auto set to validate, and another with hbm2ddl.auto set to create. I hoped that the following code would have allowed me to read from the tests the basic file and override the only hbm2ddl.auto propery, but it doesn't work (the value of hbm2ddl.auto is still the one read from hibernate.cfg.xml.

Configuration configuration = new Configuration();
configuration = configuration.
    configure("hibernate.cfg.xm开发者_运维知识库l").
    addResource("hibernate-test.cfg.xml");

How can I have two different values for a property, without replicating the whole config file?


It seems to me that when you have only a few values to override, one simple approach is to load the xml config as usual, and then call setProperty programmatically, like this:

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

hbm.xml files don't allow to override values with addResource(...) as I tried to do, the values are only added and not overridden


I had that problem with trying to programmatically load another config. Work around i used was to have another hibernate.properties file (instead of xml config). You can set the alternate hibm2ddl value in this properties file and load it using following code:

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

Try and see if this works for you.

Imp: don't call configuration.configure().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜