有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组织。冬眠休眠异常:/hibernate。cfg。在资源中找不到xml

我有一个新的spring boot项目。我使用gradle作为构建管理器和Eclpice IDE。我想使用hibernate并尝试从hibernate获取配置。cfg。xml文件,但获取

org.hibernate.HibernateException: /hibernate.cfg.xml not found

我将此文件存储在resources文件夹中,并尝试将其放入META-INF文件夹中

文件夹结构:

enter image description here

冬眠。爪哇:

public class HibernateUtil {

private static  SessionFactory sessionFactory = buildSessionFactory();


 private static SessionFactory buildSessionFactory()
   {
      try
      {
         if (sessionFactory == null)
         {
             sessionFactory = new Configuration().configure().buildSessionFactory();
         }
         return sessionFactory;
      } catch (Throwable ex)
      {
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
 }

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void shutdown() {
    // Close caches and connection pools
    getSessionFactory().close();
}

}


共 (2) 个答案

  1. # 1 楼答案

    如果要读取resources目录中的文件,需要使用classloder来获取文件

    静态法

    HibernateUtil.class.getClassLoader().getResource("hibernate.cfg.xml").getFile();
    

    非静态法

    getClass().getClassLoader().getResource("hibernate.cfg.xml").getFile();
    

    如果资源位于resources的任何子目录中,则在获取资源时为文件夹路径添加前缀

    获取META-INF目录中资源的示例

    getResource("META-INF/hibernate.cfg.xml");
    

    但是spring boot会自动配置,只需在pom.xml中添加依赖项,并在application.properties中提供与JPA相关的属性即可

  2. # 2 楼答案

    如果您的应用程序是web服务,那么应该将其置于hibernate。cfg。WEB-INF floder中的xml。如果你的应用程序是客户端服务,你应该把你的hibernate。cfg。src包中的xml