1

以前は、hibernate.cfg.xml ファイルと hibernate.properties ファイルを Java ソース フォルダーの同じフォルダーに配置していました。ここで、hibernate.properties ファイルを別の場所に移動しました。hibernate.cfg.xml ファイルで hibernate.properties ファイルを再度検出するにはどうすればよいですか? もう見つからないことを示すエラーが表示されます。

4

1 に答える 1

6

プログラムで、次のようにXMLとプロパティをロードできます。

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

お役に立てば幸いです。

于 2012-11-09T08:21:02.737 に答える