2013-04-02 64 views
2

我使用Hibernate 4.1 GWT应用上码头1.6 运行得到了下一个代码,以便启动hib.instance:Hibernate无法读取hibernate.cfg.xml中

Configuration configuration = new Configuration().configure(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml"); 
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 
sessionFactory = configuration.buildSessionFactory(serviceRegistry); 

第一行给了我一个错误:

org.hibernate.HibernateException: ...hibernate.cfg.xml not found 
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) 

但我只是装载hib.config前检查hibernate.cfg.xml可用性:

File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml"); 
System.out.println(conf.canRead()); 

Sysout返回true。

展望的ConfigHelper.getResourceAsStream源在其断点:

InputStream stream = null; 
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
if (classLoader!=null) { 
    stream = classLoader.getResourceAsStream(stripped); 
} 
if (stream == null) { 
    stream = Environment.class.getResourceAsStream(resource); 
} 
if (stream == null) { 
    stream = Environment.class.getClassLoader().getResourceAsStream(stripped); 
} 
if (stream == null) { 
    throw new HibernateException(resource + " not found"); 
} 

我做错了(不明白的地方),或它在这里真的没有XML装载机?

回答

1

这种方式自定义位于配置文件加载:

File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml"); 
Configuration configuration = new Configuration().configure(conf.getAbsoluteFile()); 

FYC:configure()方法重载

1

我会告诉你,程序不会永远不会对你。 关于你的问题,你可以这样做,以获得配置文件的路径:

String basePath = PropertiesUtil.class.getResource("/").getPath(); 

然后将其读

InputStream in = new FileInputStream(basePath + fileName); 

祝你好运!

+0

从中jar文件是否可以导入PropertiesUtil类..? – pudaykiran

+0

PropertiesUtil只是我的属性文件util-class,它不是绝对的,classpath中的任何类都可以,例如当前类。这只是为了获得classloader路径。 –

3

这里有几个错误。

首先,这样的:

Configuration configuration = new Configuration().configure(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml"); 

没有做什么,你认为它。

您的示例没有检查配置文件的可用性。它检查文件是否存在于文件系统中,而不是在类路径中。这种差异很重要。

不知道更多关于如何构建和部署您的web应用程序或如何组织您的文件,除了尝试将“hibernate.cfg.xml”复制到您的根目录之外,很难给出任何更具体的建议classpath,并将其传递给configure()方法。这应该工作。

所以,你的代码应该是:

Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); 

而且你的hibernate.cfg.xml文件应该是在你的classpath的根目录。另外,如果您使用的是Maven,只需将它放在“resources”文件夹下,Maven就可以为您完成其余的工作。

+0

谢谢,这有助于我理解。没有看到其他的'config()'方法可用。 – Minolan