从jar自动检测Hibernate中的类

时间:2013-08-02 08:47:43

标签: java hibernate java-ee jboss

我有一个带有以下persistence.xml文件的几个实体的JavaEE项目:

...
<properties>
    <!-- Scan for annotated classes -->
    <property name="hibernate.archive.autodetection" value="class"/>
...

它似乎有效。然后将该项目作为JAR部署到两个不同的项目中。在其中一个中,persistence.xml文件与上面的文件基本相同,即使用Hibernate的autodetection功能。但是,它似乎不起作用(因为我认为它需要加载搜索jar中的实体)。当我尝试手动列出两个xml文件中的所有实体时,一切正常。

编辑它适用于 jar-file ,但只能使用jar的绝对路径。对团队项目来说没用。

3 个答案:

答案 0 :(得分:3)

如果我没有正确地阅读,如果它不起作用,那么实体与使用的persistence.xml在不同的 JAR中,对吗?

我认为你的问题是正确的。你需要告诉Hibernate使用 jar-file 元素扫描哪些JAR。 请参阅Hibernate docs here

中的说明和示例

答案 1 :(得分:0)

我认为Hibernate只扫描jar文件中的JPA实体,而不是例如类/文件夹中的JPA实体,或者它只使用persistence.xml或类似的东西在jar中扫描。我没有尝试弯曲Hibernate扫描仪,而是觉得自己扫描实体会更容易。这比我预想的要容易得多。

 val entities = mutableListOf<Class<*>>()
AnnotationDetector(object : AnnotationDetector.TypeReporter {
    override fun reportTypeAnnotation(annotation: Class<out Annotation>?, className: String?) {
        entities.add(Class.forName(className))
    }

    override fun annotations(): Array<out Class<out Annotation>> = arrayOf(Entity::class.java)
}).detect("com.github")

VaadinOnKotlin.entityManagerFactory = Persistence.createEntityManagerFactory("sample", mapOf(AvailableSettings.LOADED_CLASSES to entities))

我使用了大气jar文件中内置的探测器;但您可以使用https://github.com/rmuller/infomas-asl或其他人在此处说明:Scanning Java annotations at runtime 完整的代码示例位于:https://github.com/mvysny/vaadin-on-kotlin/blob/master/vok-example-crud/src/test/java/com/github/vok/example/crud/Server.kt

以下任何一项都没有帮助:添加

<exclude-unlisted-classes>false</exclude-unlisted-classes>

persistence.xml文件什么也没做(根据doc,它在JavaSE中被忽略了);添加

<property name="hibernate.archive.autodetection" value="class, hbm" />

persistence.xml文件什么也没做(我还没有使用hbm)。不要浪费你的时间来添加它们,他们不会启用正确的自动扫描。

答案 2 :(得分:0)

使用空元素<jar-file></jar-file>可以使用,例如与WildFly 8.2.1.Final(Hibernate 4.3.7.Final):)一样提到here。 (<property name="hibernate.archive.autodetection" value="class, hbm" />无效)

(但是它在WildFly之外没有用于Eclipse运行的JUnit测试,我们不得不删除它。这不是问题,因为库已经在类路径中。错误类似于:java.net.URISyntaxException: Expected scheme-specific part at index 5: file:> => <java.lang.IllegalArgumentException: Unable to visit JAR file:. Cause: Expected scheme-specific part at index 5: file:> => <javax.persistence.PersistenceException: Unable to build entity manager factory