Hibernate OGM basics with MongoDB
Hello Guys,
We are back after long time.
From this post we started new vertical which is combination of MongoDB and Hibernate.
Yes, I am talking about Hibernate OGM.
You will find other verticals on this blog for MongoDB, Hibernate ORM and Spring Boot, please go through it if you want to brush up your knowledge.
What is OGM
In short, OGM means Object Grid Mapping.
In lil large term OGM provides support for NoSQL databases using JPA. The important part is it uses Hibernate ORM’s core engine to perform any operation with NoSQL data store.
You can find more on official site: http://hibernate.org/ogm/
The aim to start this blog series is to show how to use Hibernate OGM with MongoDB. So let’s start with basic setup of MongoDB and java project.
Developer Prerequisites
- Should have knowledge of basic MongoDB commands.
- Should have knowledge of basic SQL queries.
- Hoping you are java guy (as we are showing all demos using java and java tools).
Tools and Technology
- Eclipse
- Maven
- MongoDB
MongoDB Setup
To run and test the demo you need to setup a MongoDB in your local machine. Link below shows step-by-step guide to download, configure and sample command to check whether it is working or not.
http://www.kode12.com/kode12/mongodb/mongodb-basic-installation/
The installation guide blog was written before a year or two so may it shows some old version of MongoDB but you can use as per your machine/operating system configuration.
Create Sample Project
- Here we are using eclipse and maven to create a project.
- Select File -> New -> New Maven Project.
- Select
maven-archtype-quickstart
artifactId to create maven project with minimal configuration. - Follow the wizard to create project.
On finish you will have a project ready in your eclipse and it looks like screen below
Configure Dependency in pom.xml
First we need to define parent dependency using tag so other dependency having same
groupId
can use this dependency as a parent.
<dependencyManagement> <dependencies> <dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-bom</artifactId> <version>5.0.0.Final</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
Now we declare actual NoSQL specific dependency to get required libraries, as we are working on MongoDB demos so we need to add hibernate-ogm-mongodb
to get related dependency.
Add below snippet in your pom
<dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-mongodb</artifactId> <version>5.0.0.Final</version> </dependency>
So overall your pom.xml looks like
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.kode12</groupId> <artifactId>HibernateOGM</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>HibernateOGM</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-bom</artifactId> <version>5.0.0.Final</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-mongodb</artifactId> <version>5.0.0.Final</version> </dependency> </dependencies> </project>
Once you made these changes maven will download all required libraries and import it in your project.
Create persistence.xml
As we are using JPA to run this demo so we need to provide configuration using persistence.xml
file.
Create persistence.xml file in src/java/resource/META-INF
path, find location in screen below.
Add code below in your persistence.xml file.
<?xml version="1.0" encoding="utf-8"?> <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="myPu" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <properties> <property name="hibernate.ogm.datastore.provider" value="mongodb" /> <property name="hibernate.ogm.datastore.database" value="kode12" /> <property name="hibernate.ogm.datastore.host" value="localhost" /> <property name="hibernate.ogm.datastore.create_database" value="true" /> <property name="hibernate.ogm.datastore.username" value="root" /> <property name="hibernate.ogm.datastore.password" value="root" /> </properties> </persistence-unit> </persistence>
Now let’s go through each configuration line by line
<persistence-unit name="myPu" transaction-type="RESOURCE_LOCAL">
: This tag is a parent tag of whole persistence and name attribute should contains unique name, here we used “myPu” as a name so we can get this particular configuration from java code.<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
: Using provider tag we can provide a provider for Hibernate OGM. In our case we usedorg.hibernate.ogm.jpa.HibernateOgmPersistence
.<property name="hibernate.ogm.datastore.provider" value="mongodb" />
:hibernate.ogm.datastore.provider
is used to provide datastore provider for this persistence, here we are using MongoDB so string constant for MongoDB is “mongodb
”<property name="hibernate.ogm.datastore.database" value="kode12" />
:hibernate.ogm.datastore.database
provides name of database to be used. I want my database name to be “kode12
”.<property name="hibernate.ogm.datastore.host" value="localhost" />
:hibernate.ogm.datastore.host
is used to provide MongoDB server host address, I used “localhost ” as I have MongoDB installed in my local machine. You can use IP address or hostname on which your MongoDB is reachable.<property name="hibernate.ogm.datastore.create_database" value="true" />
:hibernate.ogm.datastore.create_database
is inform OGM engine to create new database if it is not there, in MongoDB once we execute<dbName>
anddb.collectionName.insert({…});
it will automatically create database and collection in that database if it is not there.<property name="hibernate.ogm.datastore.username" value="root" />
:hibernate.ogm.datastore.username
provides username to access your MongoDB instance. You can remove this tag if you don’t have any authentication enabled.- ><property name=”hibernate.ogm.datastore.password” value=”root” />:
hibernate.ogm.datastore.password
provides password to access your MongoDB instance. You can remove this tag if you don’t have any security enabled.
Apart from this we will have a vast number of properties and configuration available, may we use in our upcoming posts/demos.
So your typical persistence.xml
looks like
<?xml version="1.0" encoding="utf-8"?> <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="myPu" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <properties> <property name="hibernate.ogm.datastore.provider" value="mongodb" /> <property name="hibernate.ogm.datastore.database" value="kode12" /> <property name="hibernate.ogm.datastore.host" value="localhost" /> <property name="hibernate.ogm.datastore.create_database" value="true" /> <property name="hibernate.ogm.datastore.username" value="root" /> <property name="hibernate.ogm.datastore.password" value="root" /> </properties> </persistence-unit> </persistence>
Create POJO
As Hibernate OGM provides capability to map your object with your collection (in MongoDB term), actually we need JPA entity to work with Hibernate OGM so we create one POJO class. Apart from POJO class we created Utility class to create and close EntityManagerFactory
and finally created a sample class with main method to show how to insert data in MongoDB using Hibernate OGM.
Let’s see all of the classes one by one, before we move ahead please find package structure and classes created in project in screen below.
Employee.java
We declared this class as a JPA entity, also used @Id
and @Generatedvalue
annotation to define id field as primary key and should be auto generated.
Those who have an experience with JPA can easily understand this annotation.
Your Employee.java
looks like
package com.kode12.vo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + "]"; } }
HibernateOGMUtil.java
This class is created to load configuration from persistence.xml, create EntityManagerFactory and close it.
package com.kode12.util; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class HibernateOGMUtil { private static EntityManagerFactory entityManagerFactory = null; static { try { entityManagerFactory = Persistence.createEntityManagerFactory("myPu"); } catch (Exception e) { System.err.println("Initial EntityManagerFactory creation failed." + e); } } public static EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } public static void closeEntityManagerFactory() { entityManagerFactory.close(); } }
Here line entityManagerFactory = Persistence.createEntityManagerFactory("myPu");
Is responsible to create new EntityManagerFactory
and we provides name of persistent which needs to be loaded, here string constant “myPu
” is a name of persistent which we already defined in persistence.xml
DataInsertMain.java
This class shows steps to get EntityManagerFactory
, get EntityManager
, transactions, and how to persist any record using Hibernate OGM to mongoDB.
package com.kode12.crud; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import com.kode12.util.HibernateOGMUtil; import com.kode12.vo.Employee; public class DataInsertMain { private static EntityManagerFactory entityManagerFactory; public static void main(String[] args) { /* Line 1 */ entityManagerFactory = HibernateOGMUtil.getEntityManagerFactory(); /* Line 2 */ EntityManager em = entityManagerFactory.createEntityManager(); /* Line 3 */ Employee employee = new Employee(); /* Line 4 */employee.setName("Yogesh"); /* Line 5 */ em.getTransaction().begin(); /* Line 6 */ em.persist(employee); /* Line 7 */ em.getTransaction().commit(); /* Line 8 */ em.close(); /* Line 9 */ HibernateOGMUtil.closeEntityManagerFactory(); } }
Line 1 is used to get EntityManagerFatory
using our generic util class.
Line 2 show a new EntityManager
to perform out operation.
Line 3 & 4 is used to create instance of Employee class.
Line 5 will begin a transaction.
Line 6 will send an employee object for saving
Line 7 will commit the transaction
Line 8 and 9 is used to close EntityManager
and EntityManagerFatory
respectively.
Verify Data
Once you run this class you can verify data from your MongoDB console.
Check database
>show dbs; Kode12 0.078GB Test 0.078GB
Check collection
>Use kode12 >Show collections; Employee Hibernate_sequences
Hibernate_sequences
is a collection created by hibernate to maintain sequence for id
field.
To view data
>db.Employee.find(); { "_id" : NumberLong(1), "name" : "Yogesh" }
Output shows the records which is inserted using java code.
Hope you enjoyed whole journey to setup MongoDB and hibernate OGM.
Thanks for reading.
Yogesh Prajapati Hello , very nice article to demonstrate the use of Hibernate OGM with mongoDB .
Hello,
it would be faboulous if you load the (working) code of these example. Actually I cannot find any working example like yours, neigther on the official repository (https://github.com/hibernate/hibernate-ogm) : it does not compile!
Thank you very much!
Socket Time out Exception every time it try to connect to mongo
Rajan,
Can you provide full stacktrace ?