【问题标题】:could not locate cfg.xml for hibernate找不到用于休眠的 cfg.xml
【发布时间】:2017-11-02 07:20:39
【问题描述】:

我正在尝试使用 hibernate 将一个正常的插入代码连接到 mysql 数据库并为此出错,我在下面写了异常详细信息。

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/home/controller/Documents/sts_work/webtracker/src/main/java/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:258)
    at testHBConnection.main(testHBConnection.java:12)

我用于测试的 java 文件是

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

import com.ar.entity.Student;

public class testHBConnection {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        SessionFactory sf=new Configuration().configure("/home/controller/Documents/sts_work/webtracker/src/main/java/hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();
        Session ses=sf.getCurrentSession();
        try {
            Student stu= new Student("","name");

            ses.beginTransaction();
            ses.save(stu);

            ses.getTransaction().commit();

        }
catch(Exception e) {
    System.out.println("Exception "+e);

}
        finally{


        }

    }

}

我在下面链接了我的项目结构

其中 Student 是关联到数据库表的 pojo 文件 我该如何解决这个问题?

【问题讨论】:

  • 您确定 hibernate.cfg.xml 存在于绝对位置吗?

标签: java hibernate jakarta-ee


【解决方案1】:

你不能使用这条路

/home/controller/Documents/sts_work/webtracker/src/main/java/hibernate.cfg.xml

因为configure() 方法等待类路径资源(由类加载器加载)或 URL。

当然,最好使用资源。因此,如果您在 src/main/java/ 中有 hibernate.cfg.xml,则根本不需要指定它的路径:

new Configuration().configure()

有一件棘手的事情。例如,当您构建一个 jar 并运行它时,它将起作用。如果您想从 IDE 运行应用程序,在某些情况下,最好在项目配置的类路径中检查 hibernate.cfg.xml。

但更专业的方法是将hibernate.cfg.xml 放在resources文件夹中,例如,如果您使用 Maven 或 gradle。

【讨论】:

  • 将cfg.xml文件重定位到src/main/java后问题解决
  • @AllahRakha 它已经在那里了。不? src/main/java/hibernate.cfg.xml
  • 不,我将它重新定位在 src/main/java/ ,现在它可以工作了
猜你喜欢
  • 2013-08-14
  • 1970-01-01
  • 2014-11-28
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
相关资源
最近更新 更多