Hibernate XML configuration file “hibernate.cfg.xml†is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error :
(HibernateUtil.java:8)To ask Hibernate look for your “hibernate.cfg.xml†file in other directory, you can modify the default Hibernate’s SessionFactory class by passing your “hibernate.cfg.xml†file path as an argument into the configure() method:
at com.mkyong.common.App.main(App.java:11)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 2 more
SessionFactory sessionFactory = new AnnotationConfiguration().configure("/conf/hibernate.cfg.xml").buildSessionFactory();Another alternate way to load “hibernate.cfg.xml†file is by using absolute path as below
File f = new File("D:\\Workspace\\Kepler\\HibernateExamples\\conf\\hibernate.cfg.xml");
SessionFactory sessionFactory = new AnnotationConfiguration().configure(f).buildSessionFactory();
HibernateUtil.java
Full Example in HibernateUtil.java, to load “hibernate.cfg.xml†from directory “/conf/“.package com.tutorialsdesk.hibernate;
import java.io.File;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
//File f = new File("D:\\Workspace\\Kepler\\HibernateExamples\\conf\\hibernate.cfg.xml");
return new AnnotationConfiguration().configure("/conf/hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
Source:http://www.tutorialsdesk.com/2014/11/how-to-load-hibernatecfgxml-from.html
Tidak ada komentar:
Posting Komentar