Automatic JPA 2 Metamodel Generation Using Hibernate 5 and Gradle
09.02.2016 - Johann Schenkl
JPA 2 Metamodel
The JPA 2 Metamodel provides a way to create JPA Criteria Queries in a type-safe manner. For Maven, there’s an integration provided directly by Hibernate. In this post, we’ll have a look at automatically generating the necessary JPA Metamodel classes with the Gradle build automation tool. Moreover, we’ll see how to use them in Spring Data JPA Specifications.
Suppose we have modeled a simple domain entity Person:
For that entity, we want to generate a metamodel class like the following:
Setting up the Gradle build file
To automate the generation process with Gradle, we use the jpamodelgen-plugin. That plugin supports JPA Metamodel generation with Hibernate as the persistence provider out of the box.
With a little gradle scripting, the build.gradle file looks as follows:
The plugin already provides an integration in the Gradle build lifecycle. The generation happens before the compileJava task. Moreover, the generated files are deleted when executing the clean task.
Please note, that we’ve switched to Hibernate version 5.0.7.Final. Moreover, we’ve added a separated sourceSet for the generated sources, so that they’re available on the classpath.
Usage with Spring Data
After all that setup, it is easy to use the Metamodel classes with Spring Data Specifications:
As we’ve seen, Metamodel generation can be easily integrated into the Gradle build process. The plugin mechanism and scripting features of Gradle come in pretty handy here.
If you are interested in writing more fluid queries than possible with the Criteria API, you should definitely have a look at the QueryDSL project.