Red Hat

Getting started with Hibernate OGM

Getting started with Hibernate OGM

If you are familiar with JPA, you are almost good to go :-) We will nevertheless walk you through the first few steps of persisting and retrieving an entity using Hibernate OGM.

Table of Contents

Tools configuration

Before we can start, make sure you have the following tools configured:

  • Java JDK 6 or above

  • Maven 3.x

Hibernate OGM is published in the JBoss hosted Maven repository. Adjust your ~/.m2/settings.xml file according to the guidelines found on this webpage. In this example we will use Infinispan as the targeted datastore.

Add org.hibernate.ogm:hibernate-ogm-infinispan:4.1.0.Beta5 to your project dependencies.

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

While Hibernate OGM depends on JPA 2.0, it is marked as provided in the Maven POM file. If you run outside a Java EE container, make sure to explicitly add the dependency.

Tutorial

We will use the JPA APIs in this tutorial.

Let’s now map our first Hibernate OGM entity.

@Entity
public class Dog {
   @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "dog")
   @TableGenerator(
      name = "dog",
      table = "sequences",
      pkColumnName = "key",
      pkColumnValue = "dog",
      valueColumnName = "seed"
   )
   public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }
   private Long id;

   public String getName() { return name; }
   public void setName(String name) { this.name = name; }
   private String name;

   @ManyToOne
   public Breed getBreed() { return breed; }
   public void setBreed(Breed breed) { this.breed = breed; }
   private Breed breed;
}

@Entity
public class Breed {

   @Id @GeneratedValue(generator = "uuid")
   @GenericGenerator(name="uuid", strategy="uuid2")
   public String getId() { return id; }
   public void setId(String id) { this.id = id; }
   private String id;

   public String getName() { return name; }
   public void setName(String name) { this.name = name; }
   private String name;
}

I lied to you, we have already mapped two entities! If you are familiar with JPA, you can see that there is nothing specific to Hibernate OGM in our mapping.

In this tutorial, we will use JBoss Transactions for our JTA transaction manager. The final list of dependencies should look like this:

<dependencies>
    <!-- Hibernate OGM dependency -->
    <dependency>
        <groupId>org.hibernate.ogm</groupId>
        <artifactId>hibernate-ogm-core</artifactId>
        <version>4.1.0.Beta5</version>
    </dependency>

    <!-- standard APIs dependencies - provided in a Java EE container -->
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec.javax.transaction</groupId>
        <artifactId>jboss-transaction-api_1.1_spec</artifactId>
        <version>1.0.0.Final</version>
        <scope>provided</scope>
    </dependency>

    <!-- JBoss Transactions dependency -->
    <dependency>
        <groupId>org.jboss.jbossts</groupId>
        <artifactId>jbossjta</artifactId>
        <version>4.16.4.Final</version>
    </dependency>
</dependencies>

Next we need to define the persistence unit. Create a META-INF/persistence.xml file.

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="ogm-jpa-tutorial" transaction-type="JTA">
        <!-- Use Hibernate OGM provider: configuration will be transparent -->
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <properties>
            <!-- property optional if you plan and use Infinispan, otherwise adjust to your favorite
                NoSQL Datastore provider.
            <property name="hibernate.ogm.datastore.provider"
                      value="org.hibernate.ogm.datastore.infinispan.impl.InfinispanDatastoreProvider"/>
            -->
            <!-- defines which JTA Transaction we plan to use -->
            <property name="hibernate.transaction.jta.platform"
                      value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
        </properties>
    </persistence-unit>
</persistence>

Let’s now persist a set of entities and retrieve them.

//accessing JBoss's Transaction can be done differently but this one works nicely
TransactionManager tm = getTransactionManager();

//build the EntityManagerFactory as you would build in in Hibernate ORM
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
    "ogm-jpa-tutorial");

final Logger logger = LoggerFactory.getLogger(DogBreedRunner.class);

[..]

//Persist entities the way you are used to in plain JPA
tm.begin();
logger.infof("About to store dog and breed");
EntityManager em = emf.createEntityManager();
Breed collie = new Breed();
collie.setName("Collie");
em.persist(collie);
Dog dina = new Dog();
dina.setName("Dina");
dina.setBreed(collie);
em.persist(dina);
Long dinaId = dina.getId();
em.flush();
em.close();
tm.commit();

[..]

//Retrieve your entities the way you are used to in plain JPA
tm.begin();
logger.infof("About to retrieve dog and breed");
em = emf.createEntityManager();
dina = em.find(Dog.class, dinaId);
logger.infof("Found dog %s of breed %s", dina.getName(), dina.getBreed().getName());
em.flush();
em.close();
tm.commit();

[..]

emf.close();

private static final String JBOSS_TM_CLASS_NAME = "com.arjuna.ats.jta.TransactionManager";

public static TransactionManager getTransactionManager() throws Exception {
    Class<?> tmClass = Main.class.getClassLoader().loadClass(JBOSS_TM_CLASS_NAME);
    return (TransactionManager) tmClass.getMethod("transactionManager").invoke(null);
}

Some JVM do not handle mixed IPv4/IPv6 stacks properly (older Mac OS X JDK in particular), if you experience trouble starting the Infinispan cluster, pass the following property: -Djava.net.preferIPv4Stack=true to your JVM or upgrade to a recent JDK version. jdk7u6 (b22) is known to work on Max OS X.

A working example can be found in Hibernate OGM’s distribution under hibernate-ogm-documentation/examples/gettingstarted.

What have we seen?

  • Hibernate OGM is a JPA implementation and is used as such both for mapping and in API usage

  • It is configured as a specific JPA provider: org.hibernate.ogm.jpa.HibernateOgmPersistence

Let’s explore more in the next chapters.

back to top