我看到在建立SessionFactory时找不到hibernate.cfg.xml的问题在某些情况下是很常见的,但是我在这里的问题有些特定。即使在hibernate.cfg.xml中移动,我的项目在Eclipse中运行时也能正常工作。我可以将其留在源代码级别,然后执行以下操作:
Configuration configuration = new Configuration();
configuration = new Configuration();
configuration.configure();
或者我可以将其移动到其他位置并通过以下方式进行定义:
Configuration configuration = new Configuration();
configuration = new Configuration();
configuration.configure("/path/to/hibernate.cfg.xml");
两种方法都可以在Eclipse中使用。但是,当我构建一个可执行jar以便在其他地方运行该应用程序时,它在启动时会抱怨:
Initial SessionFactory creation
failed.org.hibernate.internal.util.config.ConfigurationException: Could not
locate cfg.xml resource [hibernate.cfg.xml]
org.hibernate.internal.util.config.ConfigurationException: Could not locate
cfg.xml resource [hibernate.cfg.xml]
我了解(或我认为是),原因是hibernate.cfg.xml并未包含在jar本身中,因此即使定义了路径,也找不到它,但是不知道如何解决它。我认为,如果我可以将文件放入jar,那么它可能会起作用(也许classpath也需要为此输入一个条目?),但实际上我不确定该怎么做。
答案 0 :(得分:0)
这主要取决于您是否正在使用框架,如果是,则取决于所使用的框架。如果您不使用任何框架,则可以在根路径中保留hibernate.cfg.xml文件。但是由于迫切需要使编码过程标准化,因此框架通常希望该文件位于您的资源文件夹中。但是,在这种情况下,您应该提供该配置文件的路径,而不是相对于根文件夹,而是整个路径。
答案 1 :(得分:0)
我认为您在这里使用绝对路径:
configuration.configure("/path/to/hibernate.cfg.xml");
相反,您应该使用classpath loader。像这样:
Resource r = new ClassPathResource("hibernate.cfg.xml")
String path = r.getURI().getPath();
configuration.configure(path);
这应该在包装罐子后起作用。