MongoDB

MongoDB with Hibernate ORM

Posted on Updated on

Hibernate OGM

Welcome to next interesting topics “NoSQL with Hibernate” ,basically Hibernate OGM ( Object graph mapping) provides JPA ( Java persistent )  for supports NoSQL solution.

Wide range of backends

OGM talks to NoSQL backends via store-specific dialects. Currently there is support for

  • Key/Value: Infinispan; Ehcache; Redis (tech preview)
  • Document: MongoDB; CouchDB (tech preview)
  • Graph: Neo4j
  • Wide-column: Cassandra (tech preview)

Rich query capabilities

Hibernate OGM supports several ways for searching entities and returning them as Hibernate managed objects:

  • JP-QL queries (we convert them into a native backend query)
  • datastore specific native queries
  • full-text queries, using Hibernate Search as indexing engine

And more…​

  • When JPA isn’t enough, Hibernate OGM extends it with family-specific and product-specific options. That way, the power of the backend is at your fingertips. All that in a type-safe way.
  • Mixing several NoSql datastores in one application, e.g. use Neo4j for your friendship graph and MongoDB for your blog posts. Or mix NoSQL and relational databases.
  • Support for implicit data migrations upon data load (later)
  • Denormalize data declaratively for faster retrieval (later)

One of most rich feature Hibernate Framework Provides us to integrate with any relational Database which enabled to plugins with most of RDMS Database. In this part, we will build a sample application program through we can integrate with mongoDB ( NoSQL ) using Hibernate OGM Framework. But prior to this,  you must have knowledge of Hibernate/JPA as well as mongoDB.

In this example, we have made a relationship between UserProfile and composite element UserSkills, so every UserProfile has some skills set. see at end snapshots attachment that stored UserProfile’s Document in MongoDB.

JTA transaction is not enabled in this part, we will cover in next part.

 

Tools Configuration:-

  1. JDK 1.7 or higher
  2. Maven 3.X
  3. MongoDB

Project hierarchy in Eclipse :-

hibernate-nosql-project-hierar

 

 

 

 

 

 

 

 

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>HibernateNoSQL</artifactId>
<packaging>jar</packaging>
<version>1.0.0</version>
<name>HibernateNoSQL</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mongodb.driver.version>2.7.2</mongodb.driver.version>
<hibernateOgmVersion>4.2.0.Final</hibernateOgmVersion>
</properties>
<dependencies>

<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-mongodb</artifactId>
<version>${hibernateOgmVersion}</version>
</dependency>
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-core</artifactId>
<version>${hibernateOgmVersion}</version>
</dependency>
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-infinispan</artifactId>
<version>${hibernateOgmVersion}</version>
</dependency>

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongodb.driver.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>

<dependency>
<groupId>jboss</groupId>
<artifactId>jbossjta</artifactId>
<version>4.2.2.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId>
<version>1.0.1.Final</version>
</dependency>
</dependencies>
</project>

HibernateMongoSessionUtils.Java : 


package com.example.app.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.ogm.cfg.OgmConfiguration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMongoSessionUtils {
	private static SessionFactory SESSION_FACTORY;
	private static ServiceRegistry SERVICE_REGISTRY;

	private HibernateMongoSessionUtils() {
	}

	public static SessionFactory getInstance() {

		if (SESSION_FACTORY == null) {
			synchronized (SessionFactory.class) {
				if (SESSION_FACTORY == null) {
					Configuration config = new OgmConfiguration().configure("hibernate.cfg.xml");
					SERVICE_REGISTRY = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
					SESSION_FACTORY = config.buildSessionFactory(SERVICE_REGISTRY);
				}
			}
		}
		return SESSION_FACTORY;

	}
}


UserProfile.Java : Entity class that contained list of embedded UserSkills.


package com.example.hibernate.model;

import java.util.Date;
import java.util.List;

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

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.IndexedEmbedded;

@Entity
public class UserProfile {

	@Id
	@GeneratedValue(generator = "uuid")
	@GenericGenerator(name = "uuid", strategy = "uuid2")
	private String id;

	private String name;
	private String email;
	private String phone;
	private String gender;
	private String dateOfBirth;

	private String summary;

	private Date created_date;
	private Date last_modified;

	@ElementCollection
	@IndexedEmbedded
	private List skills;

	public UserProfile() {
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(String dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public Date getCreated_date() {
		return created_date;
	}

	public void setCreated_date(Date created_date) {
		this.created_date = created_date;
	}

	public Date getLast_modified() {
		return last_modified;
	}

	public void setLast_modified(Date last_modified) {
		this.last_modified = last_modified;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("UserProfile [id=").append(id).append(", name=")
				.append(name).append(", email=").append(email)
				.append(", phone=").append(phone).append(", gender=")
				.append(gender).append(", dateOfBirth=").append(dateOfBirth)
				.append(", summary=").append(summary).append(", created_date=")
				.append(created_date).append(", last_modified=")
				.append(last_modified).append(", skills=").append(skills)
				.append("]");
		return builder.toString();
	}

	public List getSkills() {
		return skills;
	}

	public void setSkills(List skills) {
		this.skills = skills;
	}
}


UserSkills.Java : Embedded model class.


package com.example.hibernate.model;

import javax.persistence.Embeddable;

@Embeddable
public class UserSkills {
	private String name;

	public UserSkills() {
	}

	public UserSkills(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("UserSkills [name=").append(name).append("]");
		return builder.toString();
	}

}


Main Class


package com.example.main;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.example.app.utils.HibernateMongoSessionUtils;
import com.example.hibernate.model.UserProfile;
import com.example.hibernate.model.UserSkills;
/**
 * 
 * 
 * @author Ajay Kumar
 *
 */
public class MongoDBTest1 {
	
	public static void main(String args[]){
		
		Session session = HibernateMongoSessionUtils.getInstance().openSession();
		Transaction tx = session.beginTransaction();
		
		UserProfile userProfile = new UserProfile();
		
		userProfile.setName("Ajay Kumar Gupta");
		userProfile.setPhone("1234567890");
		userProfile.setEmail("ajay@domain.com");
		userProfile.setSummary("This is my Objective");
		userProfile.setGender("Male");
		userProfile.setDateOfBirth("02-Aug-1986");
		userProfile.setCreated_date(new Date());
		userProfile.setLast_modified(new Date());
		
		UserSkills skill1 = new UserSkills("Java,J2EE");
		UserSkills skill2 = new UserSkills("Spring");
		UserSkills skill3 = new UserSkills("Angular");
		UserSkills skill4 = new UserSkills("Big Database");
		UserSkills skill5 = new UserSkills("Hibernate");
		UserSkills skill6 = new UserSkills("C/C++");
		UserSkills skill7 = new UserSkills("Oracle");
		
		List userSkills = new ArrayList();
		userSkills.add(skill7);
		userSkills.add(skill6);
		userSkills.add(skill5);
		userSkills.add(skill4);
		userSkills.add(skill3);
		userSkills.add(skill2);
		userSkills.add(skill1);

		userProfile.setSkills(userSkills);
		
		// Save a Document into MongoDB
		session.save(userProfile);
		
		// fetch a Document from MongoDB
		System.out.println(userProfile.getId());
		UserProfile get_useProfile =  (UserProfile)session.get(UserProfile.class,userProfile.getId());
		System.out.println(" Fetch UserProfile Information :"+get_useProfile);
		
		tx.commit();
		session.close();
	}

}


hibernate.cfg.xml


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>

 <property name="hibernate.ogm.datastore.provider">mongodb</property>
 <property name="hibernate.ogm.datastore.database">myMongoDB</property>
 <property name="hibernate.ogm.datastore.host">127.0.0.1</property>
 <property name="hibernate.ogm.datastore.port">27017</property>
 <property name="hibernate.ogm.datastore.create_database">true</property>
 <property name="hibernate.ogm.mongodb.connection_timeout">1000</property>

 <mapping class="com.example.hibernate.model.UserProfile" />
 </session-factory>
</hibernate-configuration>

Stored Document in MongoDB:-

hibernate-mongodb-output

 

Thanks
Ajay kumar
———-