我正在尝试使用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{
}
}
}
我在这里链接我的项目结构如下
其中学生是pojo文件重定向到数据库表如何解决这个问题?
你不能用这条路
/home/controller/Documents/sts_work/webtracker/src/main/java/hibernate.cfg.xml
因为figure()
方法等待类路径资源(由类加载器加载)或URL。
当然,最好使用资源。因此,如果您在src/main/java/
中有hibernate. cfg.xml
,您根本不需要指定它的路径:
new Configuration().configure()
有一件棘手的事情。例如,当你构建一个jar并运行它时,它会起作用。如果你想从IDE运行应用程序,在某些情况下,最好检查项目配置中类路径中的hibernate. cfg.xml
。
但是更专业的方法是将hibernate. cfg.xml
放在资源
文件夹中,例如,如果您使用Maven或gradle。