我尝试了很多方法来解决这个错误(使用maven项目)
- 我将 hibernate.cfg.xml 文件放在 src 文件夹中,然后得到相同的错误(未找到 hibernate.properties)
- 我将 hibernate.cfg.xml 文件放入资源文件夹中,然后得到相同的错误(未找到 hibernate.properties)
- 我将 hibernate.cfg.xml 文件放在 webapp/WEB-INF 文件夹中,然后得到相同的错误(未找到 hibernate.properties)
- 我在 hibernate.cfg.xml 中编写的数据库的所有属性如下
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/testdb</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">sql123</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hbm2ddl.auto">create </property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="Employee-hbn.xml" />
</session-factory>
</hibernate-configuration>
May 22, 2018 2:28:38 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.0.Final}
May 22, 2018 2:28:38 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Could not locate cfg.xml resource [/src/main/java/hibernate.cfg.xml]
error
如果您有解决方案,请告诉我
提前致谢......
最佳答案
Could not locate cfg.xml resource [/src/main/java/hibernate.cfg.xml] error
这意味着 Hibernate 尝试在
中查找hibernate.cfg.xml
/src/main/java/hibernate.cfg.xml
。
这是一个不正确的路径。
你应该:
- 将
hibernate.cfg.xml
放入resources
文件夹中。 - 使用
Configuration configuration = new Configuration().configure()
进行配置。 - 刷新项目并检查
hibernate.cfg.xml
是否位于build
文件夹的根目录中。
一些解释:
配置配置 = new Configuration().configure()
意思相同
配置配置 = new Configuration().configure("hibernate.cfg.xml");
这一行告诉 Hibernate 在类路径的根目录中定位 hibernate.cfg.xml
。例如,如果您构建 jar
,则此文件应位于 jar
的根目录中。
对于war
,类路径的根是WEB-INF/classes
。
当您将文件放入 resources
文件夹中时,Maven 会将 resources
文件夹中的所有内容放置到类路径的根目录下(到 jar
,或 )。因此,jar
中不会有 resources
文件夹,只有其中的内容。
当您刷新项目时,您的 IDE 也会执行相同的操作。
关于java - 使用 hibernate 在 maven 项目中找不到 hibernate.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50461301/