gpt4 book ai didi

java - Hibernate 无法读取 hibernate.cfg.xml

转载 作者:行者123 更新时间:2023-11-30 06:25:19 25 4
gpt4 key购买 nike

我在 Jetty 1.6 上运行的 GWT 应用程序中使用 Hibernate 4.1获得了启动 hib.instance 的下一个代码:

Configuration configuration = new Configuration().configure(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);

第一行给我一个错误:

org.hibernate.HibernateException: ...hibernate.cfg.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)

但我在加载 hib.config 之前检查了 hibernate.cfg.xml 可用性:

File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");
System.out.println(conf.canRead());

Sysout 返回真。

查看带有断点的 ConfigHelper.getResourceAsStream 源代码:

InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader!=null) {
stream = classLoader.getResourceAsStream( stripped );
}
if ( stream == null ) {
stream = Environment.class.getResourceAsStream( resource );
}
if ( stream == null ) {
stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
}
if ( stream == null ) {
throw new HibernateException( resource + " not found" );
}

我做错了什么(不明白什么)或者这里真的没有 xml 加载器?

最佳答案

这里有几处错误。

首先,这个:

Configuration configuration = new Configuration().configure(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");

不会按照您的想法去做。

您的示例没有检查配置文件的可用性。它正在检查文件是否存在于文件系统中,而不是类路径中。这种差异很重要。

在不了解更多有关如何构建和部署 Web 应用程序或如何组织文件的情况下,除了尝试将“hibernate.cfg.xml”复制到类路径的根目录外,很难给您任何更具体的建议,然后将其传递给 configure() 方法。这应该有效。

所以你的代码应该是:

Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

并且您的 hibernate.cfg.xml 文件应该位于类路径的根目录中。

或者,如果您使用 Maven,只需将它放在“资源”文件夹下,Maven 会为您完成剩下的工作。

关于java - Hibernate 无法读取 hibernate.cfg.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com