我正在尝试使用 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 文件 我该如何解决这个问题?
最佳答案
你不能使用这个路径
/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。
关于java - 找不到 hibernate 的 cfg.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069676/