Hibernate Tips: How to automatically add Metamodel classes to your project



Get access to all my video courses, 2 monthly Q&A calls, monthly coding challenges, a community of like-minded developers, and regular expert sessions.

Join the Persistence Hub!


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.

Question:

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?

Solution:

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>

Source Code

Get the source code from GitHub

Learn More:

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.

Get it now!


Related Articles

Responses

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.