Friday 14 November 2014

Storing POJOs in MongoDB Using Morphia

Storing POJOs in MongoDB Using Morphia:

Storing data in any Database is always a challenge irrespective of the Datadabase.

MongoDB is a leading NoSQL Database.
We create pojo/entity and store the data in the Database using framework like Hibernate.

Similarly we have Morphia which helps to store the data in the MongoDB.
In this we will try to store the Person data in the MongoDB.
Person will have name, address and the hobbies.

To store the above mentioned person data, we will create the entities.
Will create the entities for Person Entity, Hobbies Entity and the Address Entity.

We will embed the Hobbies and Address entity into Person.

Entity Annotation : To Store the class in MongoDB thro' Morphia, add annotate to class as @Entity

To Suppress the class name from the Mongo Document use "noClassnameStored=true".

@Id : Entity require unique @Id values; these values are stored in the MongoDB "_id" field.

@Indexed : This annotation applies an index to a field.
           The indexes are applied when the datastore.ensureIndexes() method is called

Example : @Indexed(value=IndexDirection.ASC, name="userName", unique=true, dropDups=true)

@Embedded :  to create a class that will be embedded in the Entity.

Below is the code sample of the mentioned Entities.

package com.mongo.morphia.entity;

import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity(noClassnameStored=true)
public class Person {

@Id
@Property("id")
private ObjectId id;

private String name;
private List<Hobbies> hobbies;
@Embedded
private Address address;

public ObjectId getId() {
return id;
}

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

public String getName() {
return name;
}

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

public List<Hobbies> getHobbiess() {
return hobbies;
}

public void setHobbies(List<Hobbies> hobbies) {
this.hobbies = hobbies;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

}


package com.mongo.morphia.entity;

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {
private String number;
private String street;
private String town;
private String postcode;

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getTown() {
return town;
}

public void setTown(String town) {
this.town = town;
}

public String getPostcode() {
return postcode;
}

public void setPostcode(String postcode) {
this.postcode = postcode;
}

}



package com.mongo.morphia.entity;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity
public class Hobbies {

@Id
@Property("id")
private ObjectId id;

private String name;

public String getName() {
return name;
}

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

public ObjectId getId() {
return id;
}

public void setId(ObjectId id) {
this.id = id;
}
}
DAO class..

package com.mongo.morphia.dao;

import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;

public class PersonDAO extends BasicDAO<Person, String> {  

public PersonDAO(Morphia morphia, Mongo mongo, String dbName) {      
super(mongo, morphia, dbName);  
}
 
}





In the below class we have called the save , update , find and Delete operation. here we are using the entities to do all the operations.

package com.mongo.morphia;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.mongo.morphia.dao.PersonDAO;
import com.mongo.morphia.entity.Hobbies;
import com.mongo.morphia.entity.Address;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class Example {

public static void main(String[] args) throws UnknownHostException,MongoException {

String dbName = new String("User");
Mongo mongo = new Mongo();
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(mongo, dbName);

morphia.mapPackage("com.mongo.morphia.entity");

Address address = new Address();
address.setNumber("Q-101");
address.setStreet("M.G. Road");
address.setTown("Pune");
address.setPostcode("411001");

Hobbies hobbies = new Hobbies();
hobbies.setName("Trekking");

List<Hobbies> listHobbies = new ArrayList<Hobbies>();
listHobbies.add(hobbies);

Person person = new Person();
person.setAddress(address);
person.setName("Mr Martin d'souza");
person.setHobbies(listHobbies);

//Save Methods
PersonDAO personDAO = new PersonDAO(morphia, mongo, dbName);
personDAO.save(person);

//Find Methods
//use in a loop
for(Person personObj : datastore.find(Person.class, "hobbies.name", "Trekking")) {
System.out.println(personObj.getName());
}

//get back as a list
//List<Person> personObj1 = datastore.find(Person.class, "name", "Martin").asList();

// Get the Data Using Query Criteria
Query<Person> query = datastore.createQuery(Person.class);
query.and(query.criteria("hobbies.name").equal("Trekking"),
query.criteria("address.number").equal("Q-101"),
query.criteria("name").contains("Martin"));

QueryResults<Person> retrievedPersons = personDAO.find(query);

for (Person retrievedPerson : retrievedPersons) {
System.out.println(retrievedPerson.getName());
System.out.println(retrievedPerson.getAddress().getPostcode());
System.out.println(retrievedPerson.getHobbiess().get(0).getName());
}

//Update Methods
for (Person retrievedPerson : retrievedPersons) {

UpdateOperations<Person> updatePerson = datastore.createUpdateOperations(Person.class).set("name", "Kevin Gibbs");
datastore.update(datastore.createQuery(Person.class).field(Mapper.ID_KEY).equal(retrievedPerson.getId()), updatePerson);

//Delete Methods
//personDAO.delete(retrievedCustomer);
}
}

}

If You check the Mongo console you will find the below output ...

db.Person.find().pretty();
{
"_id" : ObjectId("5465ddf2e4b02b54a64d9fdd"),
"address" : {
"number" : "Q-101",
"street" : "M.G. Road",
"town" : "Pune",
"postcode" : "411001"
},
"hobbies" : [
{
"name" : "Trekking"
}
],
"name" : "Kevin Gibbs"
}



1 comment: