When working with metamodels in your project, you might face issues such as error: package jakarta.persistence.metamodel does not exist
errors during the build process. The original accepted solution provided uses code that is now deprecated in newer versions of Gradle. Additionally, it introduces a new generated
compile target, which can cause further complications down the road.
My proposed alternative solution aims to address these concerns by utilizing updated Gradle features and avoiding potential issues.
First, we need to include the Hibernate JPA Model Generator (the org.hibernate:hibernate-jpamodelgen
artifact) in the annotationProcessor
configuration. This configuration instructs the Java compiler to use the Hibernate JPA Model Generator during the annotation processing phase, generating JPA metamodel classes from your entities at compile-time.
dependencies {
annotationProcessor('org.hibernate.orm:hibernate-jpamodelgen:<version>')
}
Remember to replace <version>
with the desired version number.
Second, we need to configure where Gradle should place the generated source files, ensuring the IDE and the build system correctly recognize and compile these files. The following Gradle configuration achieves that by adapting the annotationProcessorGeneratedSourcesDirectory
option for each source set, storing the generated sources in a consistent and organization-friendly manner:
sourceSets.configureEach { sourceSet ->
tasks.named(sourceSet.compileJavaTaskName).configure {
options.annotationProcessorGeneratedSourcesDirectory = file("$buildDir/generated/sources/annotationProcessor/java/$sourceSet.name")
}
}
By using configureEach
, we ensure that this configuration is applied to all source sets in the project. For each source set (e.g., main
, test
), the generated source files will be organized into dedicated folders, respecting the project hierarchy.
In summary, this alternative solution avoids deprecated code and minimizes potential issues by using newer Gradle features. Adding this configuration will enable the generated JPA metamodel classes to be properly recognized, compiled, and used in the project without any issues.