Java hibernate.cfg.xml找不到hibernate.properties文件

Java hibernate.cfg.xml找不到hibernate.properties文件,java,hibernate,hibernate.cfg.xml,Java,Hibernate,Hibernate.cfg.xml,我们以前在Java源文件夹的同一文件夹中有hibernate.cfg.xml和hibernate.properties文件。现在我将hibernate.properties文件移到了另一个位置。如何使hibernate.cfg.xml文件再次找到hibernate.properties文件?我得到一个错误,似乎表明它不再被发现 您可以通过编程方式加载XML和属性,如下所示: public class MyHibernate { private static final SessionFac

我们以前在Java源文件夹的同一文件夹中有hibernate.cfg.xml和hibernate.properties文件。现在我将hibernate.properties文件移到了另一个位置。如何使hibernate.cfg.xml文件再次找到hibernate.properties文件?我得到一个错误,似乎表明它不再被发现

您可以通过编程方式加载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;
  }
}

希望它有用。

通过编程,您可以像这样加载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;
  }
}

希望它有用。

您可以通过编程方式创建配置,并手动将任何属性文件作为hibernate.property传递,如前所述;或者,如果您使用的是Spring,则可以通过编程方式创建配置,并手动将任何属性文件作为hibernate.property传递,如前所述;或者,如果您使用的是Spring,则可以通过编程方式将任何属性文件作为hibernate.property传递