【问题标题】:Get file path - Hibernate SessionFactory获取文件路径 - Hibernate SessionFactory
【发布时间】:2016-05-18 15:50:55
【问题描述】:

我需要为休眠创建一个会话工厂,但默认情况下它会查找“hibernate.cfg.xml”文件。 我没有创建这个文件。 所有休眠配置都在 Spring MVC 配置的“applicationContext.xml”文件中。我需要做的就是为Configuration类的“configure”方法提供“/WEB-INF/applicationContext”文件路径,但我不知道如何在JAVA中找到该文件的相对路径。

        public static SessionFactory createSessionFactory() {
            Configuration configuration = new Configuration();
            configuration.configure(HERE I NEED TO GET "/WEB-INF/applicationContext.xml FILE PATH");
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            return sessionFactory;  }

【问题讨论】:

  • 您似乎正在尝试将Spring 配置文件提取到Hibernate?不确定这是否正确...您可能应该尝试使用 spring 配置加载 spring 应用程序上下文,然后使用 spring 配置您的实体管理器工厂
  • 请在问题中添加applicationContext.xml。我认为,您尝试做不正确的事情。

标签: java hibernate


【解决方案1】:

Hibernate 使用 ClassLoader.getResourceAsStream("/WEB-INF/applicationContext.xml") 加载 /WEB-INF/applicationContext.xml

ClassLoader 尝试访问类路径根目录中的文件——对于 Web 应用程序,它是 war/WEB-INF/classes/。您应该将applicationContext.xml 放入war/WEB-INF/classes/applicationContext.xml 并使用

sessionFactory = new Configuration().configure("applicationContext.xml")
  .buildSessionFactory();

您不能指定/WEB-INF/applicationContext.xml,因为/WEB-INF/ 不在类路径中。

How Hibernate loads resources

如果你真的想从/WEB-INF/applicationContext.xml 获得配置,你应该使用ServletContext 获得URLapplicationContext.xmlFile path to resource in our war/WEB-INF folder?

并将 URL 传递给 ConfigurationStandardServiceRegistryBuilder,这取决于 Hibernate 版本。

重要通知

我认为,上面是毫无意义的,因为applicationContext.xml 应该具有类似hibernate.cfg.xml 的结构,而它显然没有。

【讨论】:

    【解决方案2】:

    该文件应该在您的类路径中,因此您应该能够使用类路径变量引用它:classpath:/WEB-INF/applicationContext.xml

    如果这不起作用,那么您使用类加载器加载文件,然后“询问”完整路径(但这应该不是必需的......):

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL resource = classLoader.getResource( "WEB-INF/applicationContext.xml" );
    String fullPath = resource.getPath()
    

    【讨论】:

    • 这两种解决方案都不起作用.... URL 类的资源实例为 NULL,引发 NullReferenceException。
    • 第二个必须有效...除非文件不在您的类路径中
    • 文件在WEB-INF文件夹中
    • 我怎么知道它是否在类路径中?
    • 您无法使用ClassLoader 访问WEB-INF 文件夹。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2015-09-26
    • 2011-11-16
    • 2021-09-10
    • 2012-03-25
    相关资源
    最近更新 更多