我在Jetty1.6上运行的GWT应用中使用Hibernate 4.1,获得了启动hib.instance的下一段代码:
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加载器?
发布于 2013-04-02 21:28:02
这样就加载了自定义位置的配置文件:
File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");
Configuration configuration = new Configuration().configure(conf.getAbsoluteFile());FYC:configure()方法被重载
发布于 2013-04-02 19:47:25
这里有几个地方是错的。
首先,这是:
Configuration configuration = new Configuration().configure(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");不会做你认为它做的事情。
您的示例不是检查配置文件的可用性。它正在检查文件系统上是否存在该文件,而不是类路径中。这一区别很重要。
在不了解如何构建和部署try应用程序或如何组织文件的情况下,除了尝试将"hibernate.cfg.xml“复制到类路径的根目录,并将其传递给configure()方法之外,很难给您提供任何更具体的建议。这应该行得通。
所以你的代码应该是:
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");并且您的hibernate.cfg.xml文件应该位于类路径的根目录中。
或者,如果您使用的是Maven,只需将其放在"resources“文件夹下,Maven将为您完成剩下的工作。
发布于 2013-04-02 19:04:12
我要告诉你,这个计划永远不会对你有好处。关于您的问题,您可以这样做来获取配置文件的路径:
String basePath = PropertiesUtil.class.getResource("/").getPath();那就读一读
InputStream in = new FileInputStream(basePath + fileName);祝好运!
https://stackoverflow.com/questions/15761912
复制相似问题