I know this is a old question,but it really trap me.
I take the advice of get inputsream using classLoader, code like following:
public static Session getSession() {
if (sessionFactory == null) {
InputStream xmlInputStream =
ResourceUtil.getInputStream(HibernateDBUtil.class, CFG_XML);
Scanner scanner = new Scanner(xmlInputStream);
//just a test I can read the xml file ,print content here
while(scanner.hasNext()) System.out.println(scanner.nextLine());
scanner.close();
//reget the stream
xmlInputStream =
ResourceUtil.getInputStream(HibernateDBUtil.class, CFG_XML);
Configuration cfg = new Configuration();
cfg.addInputStream(xmlInputStream).configure();
// version 4.3 's way to config
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder().applySettings
(cfg.getProperties());
StandardServiceRegistryImpl registry =
(StandardServiceRegistryImpl) builder.build();
sessionFactory = cfg.buildSessionFactory(registry);
}
return sessionFactory.openSession();
}
private static SessionFactory sessionFactory;
private static final String CFG_XML = "properties/hibernate.cfg.xml";
I confirm ResourceUtil.getInputStream is work fine,since I can print the content of hibernate.cfg.xml,but why still give me the error:
update: full stack trace:
INFO: HHH000412: Hibernate Core {4.3.0.Final} Jan 10, 2014 11:33:43 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found Jan 10, 2014 11:33:43 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist Jan 10, 2014 11:33:44 PM org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml Jan 10, 2014 11:33:44 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)atorg.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2093) at org.hibernate.cfg.Configuration.configure(Configuration.java:2074) at org.hibernate.cfg.Configuration.configure(Configuration.java:2054) at cn.edu.gdut.utils.HibernateDBUtil.getSession(HibernateDBUtil.java:49) at cn.edu.gdut.utils.HibernateDBUtil.listBasicElement(HibernateDBUtil.java:25) at cn.edu.gdut.utils.HibernateDBUtil.main(HibernateDBUtil.java:20)