Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autodetect classes in Hibernate from jar

I have a JavaEE project with several entities with the following persistence.xml file:

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

And it seems to work. The project is then deployed as a JAR to two different projects. In one them, the persistence.xml file is basically the same as the one above, i.e. uses the autodetection feature of Hibernate. However, it does not seem to work (because I think it needs to load search for the entities in a jar). When I tried manually listing all the entities in both xml files, everything works correctly.

Edit: It works with jar-file but only with the absolute path to the jar. Pretty useless for a team project.


2 Answers

If I read you correctly, in the case where it does not work, the entities are in a different JAR than the persistence.xml that's used, right?

I think you're correct that's the problem. You need to tell Hibernate which JAR(s) to scan using the jar-file element. See the explanation and examples in the Hibernate docs here

like image 82
Jeroen K Avatar answered Sep 18 '25 19:09

Jeroen K


I think Hibernate only scans for JPA Entities inside jar files, and not in classes/ folders for example, or it only scans in the jar with the persistence.xml, or something like that. Instead of trying to bend the Hibernate scanner, I felt it would be easier to scan for entities myself. It is a lot easier than I anticipated.

 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))

I have used the detector which is built-in in the atmosphere jar file; but you can use perhaps https://github.com/rmuller/infomas-asl or others as stated here: Scanning Java annotations at runtime The full code example is located here: https://github.com/mvysny/vaadin-on-kotlin/blob/master/vok-example-crud/src/test/java/com/github/vok/example/crud/Server.kt

None of the following helped: adding

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

to the persistence.xml file did nothing (according to doc it is ignored in JavaSE anyway); adding

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

to the persistence.xml file did nothing (I'm not using hbm anyways). Don't waste your time trying to add those, they won't enable proper auto-scan.

like image 36
Martin Vysny Avatar answered Sep 18 '25 19:09

Martin Vysny