Kick off your first JPA2 with Hibernate code

 Since Hibernate 3.5 CR2 was released recently, and the GA release is just around the corner, I decided to pick and test it as a JPA2 provider. I tried to Google for a "step-by-step" or even a sample project which uses JPA2 with Hibernate as its provider and haven't found any, so I decided to publish (the first?) one.

I tried to make this sample as simple as possible, yet demonstrate one of the innovation of JPA2: Type-safe Critaria API. Hibernate 3.5 uses a Java 6 annotation processor used to generate JPA 2 StaticMetamodel classes, intended mostly for use in JPA 2 criteria queries. The processor (JPAMetaModelEntityProcessor) processes all classes annotated with @Entity, as well as entities mapped in /META-INF/orm.xml and mapping files specified in persistence.xml.
On our example we'll have a "User" entity, and the processor will create a metamodel class "User_". The generated "User_" class enable us to run a type-safe criteria query. The generation of this class can be created either by the IDE or by a build tool (or both).

So without further words, lets start our first Maven JPA2+Hibernate project:
First we need to create the pom.xml which declares all the dependencies (including the Hibernate preprocessor jar to generate our "User_" class)


<project xmlns="" xmlns:xsi=""


    <name>Maven Quick Start Archetype</name>


        <!-- concrete Log4J Implementation for SLF4J API-->

        <!-- Hibernate generate Metamodel -->

        <!-- Hibernate dependecies -->



                            <!-- source output directory -->




Now, lets create a simple entity "User":


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

public class User {

	User() {

	public User(String name) { = name;

	private Integer id;

	private String name;

	public String getName() {
		return name;



Next step is to create create a persistence.xml file under META-INF directory containing the DB properties (HSQL in memory DB in our case) , the entities , and a couple of Hibernate properties (auto-generate the schema and SQL dialect):

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns=""
             xsi:schemaLocation=" persistence_2_0.xsd"

    <persistence-unit name="sampleEM" transaction-type="RESOURCE_LOCAL">

            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:aname"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <!-- Hibernate required props -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="" value="update"/>




Thats all the source needed for the project!

Now you need to run "mvn install". This will generate java sources for the metamodel and compile it with all other Java sources in the project. In our case a new Java file, will be created at target/metamodel/com/tikal/sample/model folder:

public abstract class User_ {

    public static volatile SingularAttribute<User, Integer> id;

    public static volatile SingularAttribute<User, String> name;



Lets unit test the code above, by creating a type-safe criteria query.


public class UserTest {

    private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("sampleEM");

    public void findUsers() {

        String name = "yanai";
        EntityManager em = factory.createEntityManager();
        EntityTransaction tx = null;
        try {
            tx = em.getTransaction();
            em.persist(new User(name));
            User loadedUser = loadUserByName(name, em);
            assert loadedUser.getName().equals(name);
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive())
            throw e;
        } finally {

    private User loadUserByName(String name, EntityManager em) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<user> q = cb.createQuery(User.class);
        Root<user> user = q.from(User.class);, name));
        return em.createQuery(q).getSingleResult();


If you look carefully at the "loadUserByName" method you can see that we use the "" as a type-safe predicate for our query:, name));


Thats all. I hope this post helped you kick off and taste JPA2 with Hibernate.