2009-12-13

Generating JPA 2.0 Criteria canonical metamodels with Maven and NetBeans

Updated on August 23, 2011: Hibernate, OpenJPA and DataNucleus documentation links.
Updated on July 25, 2012: The DataNucleus documentation link, pom.xml snippet.

Java EE 6 and JPA 2.0 bring us a neat feature from Hibernate: Criteria queries, which allow you to construct complex database queries in a safe manner, instead of trying to append pieces of SQL or JQL together, and hoping that the result doesn't allow injection attacks.

That's all well and good, but JPA 2.0 adds a wrinkle: instead of using simple strings to construct Criteria queries, one must generate metamodel classes, out of the entity classes. This is done by using the Java 6 APT annotation pre-processor.

Unfortunately, Maven doesn't support this kind of generation process very well out of the box. There are, however, various plugins such as the maven-annotation-plugin and apt-maven-plugin to help with this process.

I am still in the process of figuring out which way of generating the classes is the best, where they should go, and how to handle the process in a way which doesn't tie one to a specific JPA provider.

NetBeans has its own opinion on how the generated classes should be handled, as well.

Meanwhile, these are the best resources I've found for generating metamodels for various JPA implementations:

EclipseLink

org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
http://wiki.eclipse.org/UserGuide/JPA/Using_the_Canonical_Model_Generator_(ELUG)

Hibernate

org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
http://docs.jboss.org/hibernate/stable/jpamodelgen/reference/en-US/html_single/

OpenJPA

org.apache.openjpa.persistence.meta.AnnotationProcessor6
http://openjpa.apache.org/builds/2.1.0/apache-openjpa-2.1.0/docs/manual/ch13s04.html

DataNucleus

http://www.datanucleus.org/products/accessplatform/jpa/jpql_criteria.html

Edit: this works for me with Hibernate.

3 comments:

  1. Hi Mikael, thanks a lot for this blog, it helped me make the metamodel generation work in Maven. We are now trying to make this work out of the box for NetBeans 6.9 - see also this bug report, which has some Maven-specific comments: http://netbeans.org/bugzilla/show_bug.cgi?id=178108#c27.

    One question about your pom file - is it really necessary to have the dependencies section inside the maven-processor-plugin definition? It worked for me even without it, by just specifying the project dependencies. Thanks,
    Petr

    ReplyDelete
  2. Really nice thank you very much

    ReplyDelete
  3. Hi there. I have a question, though. Are those generated classes packed into your WAR file?

    Thanks,
    PP

    ReplyDelete