Hibernate Tips: How to automatically add Metamodel classes to your project
Take your skills to the next level!
The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, 2 monthly Q&A calls, monthly coding challenges, a community of like-minded developers, and regular expert sessions.
Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
I use Hibernate’s Static Metamodel Generator to generate the JPA Metamodel. These classes are generated to a different directory which isn’t used as a source folder. Is there any way to automatically register this folder as a source folder?
This is a question I asked myself and the reviewers of my book. As I learned, there is a Maven plugin which can do exactly that. Special thanks to Frits Walraven who’s reviewing the book and showed me the plugin.
The only thing you need to do is to add the following Maven plugin to your build configuration. It registers a list of directories as additional source folders. I use it in the parent pom file of my project to add the directory, to which the JPA Metamodel classes get generated target/generated-sources/annotations, as a source folder.
<project> ... <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>target/generated-sources/annotations</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> ... </project>
Get the source code from GitHub
The JPA Metamodel provides a type-safe way to reference entity attributes when you create a CriteriaQuery or an EntityGraph.
I explain it in more detail in: Create type-safe queries with the JPA static metamodel.
Hibernate Tips Book
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.