Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top