Saturday, August 17, 2013

Java Persistency API 2.0 (JPA): Hibernate JPA Metamodel Generator With Eclipse and Maven

One of the key features introduced in JPA 2.0 is the Criteria API, which brings a unique capability to the Java language: a way to develop queries that a Java compiler can verify for correctness at compile time. The Criteria API also includes mechanisms for building queries dynamically at run time.

In this post, I will share my experience how I configured my Eclipse to create Static Meta Model classes.


Since the Static Meta Model files are generated classes and should automatically changed for each @Entity modification they should placed in the target folder and not comitted to the repository.


Below are the steps that you have to follow:


1. Update pom.xml file:

Please update your pom.xml file with the below code under <dependencies></dependencies>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <version>1.3.0.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

2. Configure Eclipse:
Right click on your project -> properties -> Java compiler-> Annotation processing -> mark "enable project specific settings" (rather all the checkboxes on that screen), in the Generated Source Directory put "target/metamodel". 
Screenshot given below:


















Once done, Inside the Annotation processing item there is a Factory Path item. You have to enable this where you have to set the jar you imported via maven to generate the classes. 
You can do it by clicking Add Variable -> M2_REPO -> Extend -> and choose the following path : 


org\hibernate\hibernate-jpamodelgen\1.3.0.Final\hibernate-jpamodelgen-1.3.0.Final
Below is the screenshot:















You have to make sure only that path is checked.

3. Final steps/Adjust Classpath:
Please make sure the target/metamodel folder is on your classpath (right click-> build path -> ad as source folder).






















That's all. From now on every change in Entity Classes will trigger automatic Static Meta Model Generation.

Finally your project structure should look like:





0 comments:

Post a Comment