如何为具有休眠配置的 Maven eclipse 项目制作可运行的 jar 文件

How to make the runnable jar file for a maven eclipse project with hibernate configuration

我尝试使用休眠配置从我的 eclipse maven 项目创建一个 jar 文件。

这是我项目的结构,我在 resources/ 和 src/main/resources/ 文件夹中都有文件 hibernate.cfg.xml。我通过从导出选项中选择可运行的 jar 文件来制作 jar 文件。 (感谢 link 的帮助)

这是我在 运行 可执行 jar 文件时得到的错误:

ehsanik$ java -jar oh_oh.jar 
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.ExceptionInInitializerError
    at com.jvmhub.tutorial.App.StartDB(App.java:25)
    at CopyOfMain.main(CopyOfMain.java:7)
    ... 5 more
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
    at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1940)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1921)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1901)
    at com.jvmhub.tutorial.App.StartDB(App.java:19)
    ... 6 more

TL;DR-解决方案

将你的 hibernate.cfg.xml 填入 src/main/resource。然后不导出 您的项目通过 eclipse 的导出功能。而是使用 maven-assembly-plugin 来创建一个可执行的 jar。 运行 与 mvn package assembly:single.

eclipse 做了什么以及它为什么不工作

如果你在eclipse选项中选择"export",你编译的类(由eclipse编译)将被放入那个jar。但是 Eclipse 对 Maven Standard Directory Layout 一无所知。它只会将文件留在它们的文件夹中。另一方面,Maven 会将所有资源从 src/main/resources-文件夹复制到 jar 文件的根目录。

如何读取您看到的错误

第一个错误:

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.

这意味着,log4j 没有找到 log4j.properties 或 .xml。它是未配置的。这是第一个提示,您的构建不成功。

第二个错误:

Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found

第二个提示,您的资源不在库期望它们所在的位置(在本例中为休眠)。