Connecting to MongoDB in Java using Hibernate OGM

While working with Java and a MongoDB backend, I noticed that there is not much of information available on the interweb on making Java talk to MongoDB. We had to figure out and I thought someone might find this useful. Here we go:

MongoDB

MongoDB is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

Example

 {
                               "_id" : ObjectId("5719ed22ed49740ccfdd6165"),
                                "name" : "xxxx",
                                "date" : "April 14, 2016",
                         }

Hibernate OGM - Hibernate Object/Grid Mapper :

Hibernate OGM is a persistence engine providing Java Persistence (JPA) support for NoSQL.It reuses the Java Persistence Query Language (JP-QL) as an interface to querying stored data.

Hibernate Infinispan

Infinispan is an open source in-memory data grid focusing on high performance. As a data grid, you can deploy it on multiple servers - referred to as nodes - and connect to it as if it were a single storage engine: it will cleverly distribute both the computation effort and the data storage.

Infinispan can be configured in three ways:

  • Add Dependency to classpath and use the default configuration
  • Add Dependency to classpath and point to your own resource name
  • Add Dependency to classpath and point to a JNDI of an existing Infinispan instance

This blog post uses infinispan default configuration.

Hibernate Search

Hibernate Search integrates with Hibernate OGM.Using this you can configure your indexes and map entities with relevant index annotations

Project Configuration Add dependencies to pom.xml

<dependencies>  
        <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.0.0.CR1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

                                 <!-- Hibernate OGM dependency -->
  <dependency>
        <groupId>org.hibernate.ogm</groupId>
        <artifactId>hibernate-ogm-core</artifactId>
        <version>5.0.0.CR1</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>

          <dependency>
                <groupId>org.hibernate.ogm</groupId>
                <artifactId>hibernate-ogm-mongodb</artifactId>
                <version>5.0.0.CR1</version>
            </dependency>
            <dependency>
                    <groupId>org.hibernate.common</groupId>
                    <artifactId>hibernate-commons-annotations</artifactId>
                    <version>5.0.1.Final</version>
            </dependency>
            <dependency>
                    <groupId>org.hibernate.ogm</groupId>
                    <artifactId>hibernate-ogm-infinispan</artifactId>
                    <version>5.0.0.Alpha1</version>
            </dependency>
             <dependency>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-search-orm</artifactId>
                        <version>5.5.0.Final</version>
             </dependency>

             <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-io</artifactId>
                <version>1.3.2</version>
            </dependency>

                       </dependencies>

Configure persistence.xml file - META-INF /persistence.xml

<?xml version="1.0" encoding="UTF-8"?>  
<persistence version="2.0" 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">  
  <persistence-unit name="primary" transaction-type="JTA">
   <jta-data-source/>
      <properties>
      <property name="hibernate.ogm.datastore.provider" value="infinispan"/>
      <property name="hibernate.ogm.mongodb.database" value="test"/>
      <property name="hibernate.ogm.mongodb.host" value="127.0.0.1/domain/serverIP "/>
      <property name="hibernate.ogm.mongodb.port" value="27017"/>
      <property name="hibernate.ogm.mongodb.username" value="user"/>
      <property name="hibernate.ogm.mongodb.password" value="pwd"/>
    </properties>
  </persistence-unit>
</persistence>  

Configure hibernate.cfg.xml - Hostname, database, username and password fields should be modified as per the mongodb configuration

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
<hibernate-configuration>  
  <session-factory>  
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.ogm.datastore.provider">infinispan</property>
    <property name="hibernate.ogm.mongodb.database">test</property>
    <property name="hibernate.ogm.mongodb.host">hostname</property>
    <property name="hibernate.ogm.mongodb.port">27017</property>
    <property name="hibernate.ogm.mongodb.username" >user</property>
    <property name="hibernate.ogm.mongodb.password" >pwd</property>
    <property name="hibernate.search.default.directory_provider">filesystem</property>    
    <property name="hibernate.search.default.indexBase">./Indexes</property>    
    <property name="hibernate.search.default.locking_strategy">single</property>

    <mapping resource="testing.hbm.xml"/> // to map your bean with table
  </session-factory>
</hibernate-configuration>  

Create a bean and a mapping resource file to map your bean with NoSQL file

java -bean

           Testing.class

                      @Entity
@Indexed
@Table(name="test")
public class Testing{  
// Sample class for testing
     @Id
    private String id;

     @Column(name="book")
     private String book;

     @Column(name="author")
     private String author;
 }

            Testing.hbm.xml

             <?xml version="1.0" encoding="UTF-8"?>
             <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD     3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
             <hibernate-mapping>
              <class name="com.rec.bean.Testing" table="test_table">
         <id column="id" type="String">
                <generator class="native" />
         </id>
          <property name="book" type="string">
             <column name="book"></column>
         </property>

         <property name="author" type="string">
             <column name="author"></column>
         </property>
       </class>
 </hibernate-mapping>

HibernateUtil.java

public class HibernateUtil {  
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() 
    {
        if (sessionFactory == null) 
        {
             Configuration cfgogm = new OgmConfiguration().configure();
              ServiceRegistry serviceRegistry
                = new StandardServiceRegistryBuilder()
                    .applySettings(cfgogm.getProperties()).build();

             cfgogm.addAnnotatedClass(Testing.class);
            sessionFactory = cfgogm.buildSessionFactory(serviceRegistry);   
            sessionFactory.getStatistics().setStatisticsEnabled(Boolean.TRUE);
        }
        else
        {
            System.out.println("SessionFactory is not Null");
        }
        System.out.println(sessionFactory);
        return sessionFactory;
    }
       public static void main(String[] args)
    {

        SessionFactory sessionFactory = new HibernateUtil().getSessionFactory();

        if(!sessionFactory.isClosed())
        {
            System.out.println("-------------------------------------------------------------------------");
            System.out.println("SessionFactory is Still Open!! Now Attempting to close the SessionFactory");
            System.out.println("-------------------------------------------------------------------------");
            sessionFactory.close();
        }

        System.exit(0);

    }
 }

Krithika, developer at Powerupcloud, has contributed to this post

Ram Kumar

Loves writing code, reading books and singing songs. One of the first devs to commit code to Android in Open Handset Alliance days. Currently Co-Founder and Director of Engineering at Powerupcloud

comments powered by Disqus