hibernate.cfg.xml does not find hibernate.properties file

橙三吉。 提交于 2020-01-05 06:44:07

问题


We used to have the hibernate.cfg.xml and hibernate.properties files in the same folder in our Java source folder. Now I moved the hibernate.properties file to another location. How can I make the hibernate.cfg.xml file find the hibernate.properties file again? I get an error which seems to indicate that it is not found anymore.


回答1:


Programmatically, you can load XML and properties like this:

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;
  }
}

Hope it be useful.



来源:https://stackoverflow.com/questions/13304078/hibernate-cfg-xml-does-not-find-hibernate-properties-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!