org.hibernate.internal.util.config.ConfigurationException:找不到cfg.xml资源[/HibernateTest/src/hibernate.cfg.xml]

时间:2016-03-01 14:17:20

标签: java hibernate postgresql jdbc ubuntu-14.04

我正在尝试使用pgadmin3连接到ubuntu中的Postgresql9.1。 我的Pgadmin3 GUI工具没有通过右键单击数据库来提供创建表的任何选项,但在我看到的一些视频中可以使用它。因此,我使用终端来创建数据库,它出现在pgadmin3中。

my file structure

我的用户详细信息文件

package org.nitish.hiber;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int userId;
    private String userName;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

我的HibernateCaller文件

package org.nitish.caller;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.nitish.hiber.UserDetails;

public class HibernateTest {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("First User");
        try {
            SessionFactory sessionFactory = new Configuration().configure("/HibernateTest/src/hibernate.cfg.xml").buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();

        } catch(HibernateException e) {
            e.printStackTrace();
        }
    }

}

的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, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<hibernate-configuration>

  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">org.postgresql.Driver  </property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/hiber</property>
    <property name="connection.username">nitish</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <mapping class="org.nitish.hiber.UserDetails"/>
  </session-factory>
</hibernate-configuration>

我收到以下错误

Mar 1, 2016 9:02:48 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 1, 2016 9:02:48 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/HibernateTest/src/hibernate.cfg.xml]
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
    at org.nitish.caller.HibernateTest.main(HibernateTest.java:17)

进行一些更改后(在finally块中无法使用session.close()我认为不应该导致此错误)

Mar 1, 2016 10:13:34 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Mar 1, 2016 10:13:34 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 1, 2016 10:13:34 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 1, 2016 10:13:34 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Mar 1, 2016 10:13:35 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 1, 2016 10:13:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at org.nitish.caller.HibernateTest.main(HibernateTest.java:17)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.postgresql.Driver]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:161)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:117)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:73)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.postgresql.Driver
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:217)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:274)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
    ... 25 more

9 个答案:

答案 0 :(得分:9)

如果您在源文件夹的根目录中有hibernate.cfg.xml,请执行

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

如果它在包中,对于org.nitish.caller中的示例,请通过这种方式指定路径

 SessionFactory sessionFactory = new Configuration()
    .configure("/org/nitish/caller/hibernate.cfg.xml").buildSessionFactory();

您需要关闭session(在finally区块中)。别忘了添加rollback代码。

请将@Table注释添加到UserDetails

<强>更新

Hibernate无法找到org.postgresql.Driver类的错误原因。它驻留在postgresql jar中。你的图像上有那个jar,但可能是你没有将它添加到类路径中。请参阅How to Add JARs to Project Build Paths in Eclipse (Java)

要关闭session块中的finally,您需要在session块之外设置try变量。

    Session session = sessionFactory.openSession();

    try{

    } finally {
        session.close();
   }

答案 1 :(得分:1)

new Configuration().configure()从类路径目录的根目录中获取hibernate.cfg.xmlnew Configuration().configure("/com/company/project/hibernate.cfg.xml")取自类路径+ com / company / project / hibernate.cfg.xml 的根。

如果从类路径的根目录使用不同的文件名进行hibernate配置,那么例如:new Configuration().configure("/database.cfg.xml")

如果要提供配置文件的完整系统路径,则new Configuration().configure(new File("/home/visruth/config/hibernate.cfg.xml))从给定的确切位置获取配置文件。

答案 2 :(得分:1)

我通过将配置文件移动到src/mail/resources来修复此问题。对我来说,这是根目录。

答案 3 :(得分:0)

所有先前的答案都是完美的。但是,如果您需要一个非常快速的解决方案,那么我建议您只将hibernate.cfg.xml文件放在源文件夹中并编写

SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

这很简单并且有效!

答案 4 :(得分:0)

new Configuration().configure(new File("hibernate.cfg.xml")).buildSessionFactory());

这为我解决了错误!

答案 5 :(得分:0)

您必须使用文件的绝对路径,否则将无法使用。然后使用该路径构建文件,并将其传递给配置。

private fun getFile(): File {
    val currentWorkingDir = System.getProperty("user.dir")
    val absoulutePath = "$currentWorkingDir/src/main/resources/secret-hibernate.cfg.xml"
    println("Absolute Path of secret-hibernate.cfg.xml: $absoulutePath")
    return File(absoulutePath)
}

https://stackoverflow.com/a/64084771/5279996

GL

答案 6 :(得分:0)

在 src/main 中创建一个名为“resources”的文件夹 将 hiberenate.cfg.xml 文件放入其中 创建会话工厂对象为 SessionFactory factory = new Configuration().configure().buildSessionFactory();

这将成功创建对象 您可以通过检查此应打印 false System.out.println(factory.isClosed()); 来验证它;

这对我有用!

答案 7 :(得分:0)

答案就在错误(问题)的第一行,如果你仔细阅读,它说: Could not locate cfg.xml resource >> 资源

似乎在 resource 中没有找到任何东西,或者可能是 resource 没有正确设置

如果您使用的是 Intellij 等 IDE:

  • 确保将您的 hibernate.cfg.xml 保存在 src/main/resources/
<块引用>

示例:src/main/resources/hibernate.cfg.xml

  • 这很重要(我个人在 java/maven 的初始设置过程中几乎总是遇到过这个问题。)
<块引用>

因此,请确保将 resources 目录标记为资源根目录,使其看起来
例如,看看这张图片

<头>
如何将文件夹标记为资源根目录
<头>
之前 之后 (看3行)

现在编译和构建: 将构建一个新 jar,将所有文件与最新更改链接起来,您将不会再因缺少 hibernate.cfg.xml

答案 8 :(得分:0)

src根目录项目中创建一个文件,命名为:“hibernate.cfg.xml”。

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
   <session-factory>
     <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="connection.url">jdbc:mysql://localhost/hibernate1</property>     <property name="connection.username">hibernate1</property>
     <property name="connection.password">hibernate1</property>
     <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
     <property name="hibernate.show_sql">true</property>

   </session-factory>
 </hibernate-configuration>

在你的班级

  package io.yourPack;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class hibernateClass  {
    
     public static void main(String[] args) {
         
         SessionFactory myFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(clima.class).buildSessionFactory();
            
            Session mySession = myFactory.openSession();
            
            try {
                
                yourClass cl1 = new yourClass("java", "1,2,3", 6);
                
                mySession.beginTransaction();
                
                mySession.save(cl1);
                
                mySession.getTransaction().commit();
                
                System.out.println("Inserted !!");
                
                mySession.close();
                
            }finally {
                myFactory.close();
            }
         
     }
    

}