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 :-











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




HibernateMongoSessionUtils.Java : 


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);


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;

public class UserProfile {

	@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;

	private List skills;

	public UserProfile() {

	public String getId() {
		return id;

	public void setId(String id) { = id;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getEmail() {
		return email;

	public void setEmail(String email) { = email;

	public String getPhone() {
		return phone;

	public void setPhone(String 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;

	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)
		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;

public class UserSkills {
	private String name;

	public UserSkills() {

	public UserSkills(String name) { = name;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	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.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.setSummary("This is my Objective");
		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();

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



<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

 <property name="hibernate.ogm.datastore.provider">mongodb</property>
 <property name="hibernate.ogm.datastore.database">myMongoDB</property>
 <property name=""></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" />

Stored Document in MongoDB:-



Ajay kumar