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

Spring 4 with MongoDB Example-1

Posted on Updated on

mongoDB-spring

 

 

 

 

 

 

Here we will show you how to write your first Spring program with MongoDB, also will do CRUD operation.

We used following technologies and tools to configure to build in this program:-

  1. Spring Data MongoDB – 1.5.2.RELEASE
  2. Spring Core – 4.0.3.RELEASE
  3. Eclipse – 4.2
  4. JDK – 1.7
  5. Maven – 3.0.3

Maven Project Structure in eclipse :-

SpringMongoDB-Project-Arc

 

 

 

 

 

 

 

Dependency Jar file in 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">

<groupId>com.itexpert</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringMongoDBApplication</artifactId>
<name>SpringMongoDBApplication</name>
<version>1.1-SNAPSHOT</version>
<packaging>jar</packaging>

<description>
Root Project For Spring MongoDB Application
</description>
<properties>

<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<spring-data-mongodb.version>1.5.2.RELEASE</spring-data-mongodb.version>

<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>

</properties>

<dependencies>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring-data-mongodb.version}</version>
</dependency>

<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>

</dependencies>
</project>

Spring configuration with annotation:-

Here, we used annotation to connect to mongoDB.


package com.itexpert.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;

@Configuration
@ComponentScan("com.itexpert")
public class AppConfig {

	
	public @Bean MongoDbFactory mongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(new MongoClient("localhost",27017), "itexpert");
	}

	
	public @Bean MongoTemplate mongoTemplate() throws Exception {
		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
		return mongoTemplate;

	}

}


MongoDB document base Model :-

Here, UserProfile Model represents a @Document in MongoDB:


package com.itexpert.mongo.model;
/**
 * @author #Ajay
 */
import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "UserProfile")
public class UserProfile implements Serializable {

	private static final long serialVersionUID = -5048239448394661430L;

	@Id
	private String id;

	@Indexed
	private String email;

	@Indexed
	private String password;

	private String status = "Unlock";

	private String firstName;
	private String middleName;
	private String lastName;
	private String phone;

	public UserProfile(String email, String password, String status,
			String firstName, String middleName, String lastName, String phone) {
		super();
		
		this.email = email;
		this.password = password;
		this.status = status;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.phone = phone;
	}

	public String getId() {
		return id;
	}

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

	public String getEmail() {
		return email;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getMiddleName() {
		return middleName;
	}

	public void setMiddleName(String middleName) {
		this.middleName = middleName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getPhone() {
		return phone;
	}

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

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

       @Override
	public String toString() {
		return String
		.format("UserProfile [id=%s, email=%s, password=%s, status=%s, firstName=%s, middleName=%s,       lastName=%s, phone=%s]",id, email, password, status, firstName, middleName,lastName, phone);
	}

}


Spring DAO Layer

Here, We created a UserProfileRepository @Repository to access the data from mongoDB.

BaseUserDAO.Java


package com.itexpert.dao;
/**
 * @author #Ajay
 */
import java.util.List;

import com.itexpert.mongo.model.UserProfile;

public interface BaseUserDAO {
	
	public void create(T user);
	public void remove(T id);
	public void removeByEmail(String id);
	public void removeAll();
	public T find(String id);
	public List findAll();
	public void update(T user);
	public UserProfile getUserProfileByEmail(String email);

}


UserProfileRepository.Java


package com.itexpert.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.itexpert.dao.BaseUserDAO;
import com.itexpert.mongo.model.UserProfile;

/**
 * @author #Ajay
 */
@Component("userProfileRepository")
public class UserProfileRepository implements BaseUserDAO {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void create(UserProfile user) {
		mongoTemplate.save(user);
	}

	@Override
	public void removeByEmail(String userEmail) {
		if (null != userEmail) {
			Query query = new Query();
			Criteria criteria = Criteria.where("email").is(userEmail);
			query.addCriteria(criteria);
			mongoTemplate.remove(query, UserProfile.class);
		}
	}

	@Override
	public UserProfile find(String id) {
		Query query = new Query();
		Criteria criteria = Criteria.where("id").is(id);
		query.addCriteria(criteria);
		return mongoTemplate.findOne(query, UserProfile.class);
	}

	@Override
	public List findAll() {
		return mongoTemplate.findAll(UserProfile.class);
	}

	@Override
	public void update(UserProfile user) {
		mongoTemplate.save(user);

	}

	@Override
	public void removeAll() {
		mongoTemplate.dropCollection(UserProfile.class);

	}

	public UserProfile getUserProfileByEmail(String email) {
		if (email == null || email.isEmpty())
			return null;
		Query query = new Query();
		Criteria criteria = Criteria.where("email").is(email);
		query.addCriteria(criteria);
		return mongoTemplate.findOne(query, UserProfile.class);
	}

	@Override
	public void remove(UserProfile user) {

		mongoTemplate.remove(user);

	}

}

Execute Java Main Class

In this Java main class, we initialized ApplicationContext and test CRUD operation in mongoDB.


package com.itexpert.Main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.itexpert.app.config.AppConfig;
import com.itexpert.dao.impl.UserProfileRepository;
import com.itexpert.mongo.model.UserProfile;

/**
 * @author #Ajay
 */

public class AppMain {

	public static void main(String args[]) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(
				AppConfig.class);
		UserProfileRepository userRepo = (UserProfileRepository) ctx
				.getBean(UserProfileRepository.class);

		UserProfile user = new UserProfile("experts.itconsultants@gmail.com",
				"*******", "unlock", "Santosh", "Kumar", "Yadav", "011-8987898");
		// Save UserProfile Object into MongoDB
		userRepo.create(user);
		// Print Saved UserProfile Object from MongoDB
		user = userRepo.getUserProfileByEmail("experts.itconsultants@gmail.com");
		System.out.println(" Get UserProfile Record : "+user);
		// Update UserProfile's Phone into MongoDB
		user.setPhone("98987656787");
		userRepo.update(user);
		System.out.println(" Update UserProfile Record : "+user);
		// Delete UserProfile record from MongoDB
		userRepo.removeByEmail("experts.itconsultants@gmail.com");
		// Check remove Object does exist or not
		user = userRepo.getUserProfileByEmail("experts.itconsultants@gmail.com");
		System.out.println(" After Delete Operation, Get UserProfile Record : "+user);

	}
}


Output here :-

23:11:02.579 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.584 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.589 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – Saving DBObject containing fields: [_class, _id, email, password, status, firstName, middleName, lastName, phone]
23:11:02.589 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.607 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – findOne using query: { “email” : “experts.itconsultants@gmail.com”} fields: null for class: class com.itexpert.mongo.model.UserProfile in collection: UserProfile
23:11:02.608 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.608 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – findOne using query: { “email” : “experts.itconsultants@gmail.com”} in db.collection: itexpert.UserProfile
Get UserProfile Record : UserProfile [id=561164ae98809bcebee2920b, email=experts.itconsultants@gmail.com, password=*******, status=unlock, firstName=Santosh, middleName=Kumar, lastName=Yadav, phone=011-8987898]
23:11:02.616 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – Saving DBObject containing fields: [_class, _id, email, password, status, firstName, middleName, lastName, phone]
23:11:02.616 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
Update UserProfile Record : UserProfile [id=561164ae98809bcebee2920b, email=experts.itconsultants@gmail.com, password=*******, status=unlock, firstName=Santosh, middleName=Kumar, lastName=Yadav, phone=98987656787]
23:11:02.619 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.620 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – Remove using query: { “email” : “experts.itconsultants@gmail.com”} in collection: UserProfile.
23:11:02.622 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – findOne using query: { “email” : “experts.itconsultants@gmail.com”} fields: null for class: class com.itexpert.mongo.model.UserProfile in collection: UserProfile
23:11:02.622 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils – Getting Mongo Database name=[itexpert]
23:11:02.622 [main] DEBUG o.s.data.mongodb.core.MongoTemplate – findOne using query: { “email” : “experts.itconsultants@gmail.com”} in db.collection: itexpert.UserProfile
After Delete Operation, Get UserProfile Record : null