Wednesday, May 23, 2018

MongoDB CRUD Operations using Morphia

MongoDB CRUD Operations using Morphia

mongocrud

 

Establishing a connection to MONGODB


package com.mongo.test;

import java.net.UnknownHostException;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class MongoConnection {

 public static Datastore getConnection() throws UnknownHostException{
  final Morphia morphia = new Morphia();
  morphia.mapPackage("com.test.beans");
  final Datastore datastore = morphia.createDatastore(new MongoClient(new MongoClientURI("mongodb://localhost:27017")), "Test");  
  datastore.ensureIndexes();
  return datastore;    
 }
}

morphia.mapPackage("com.test.beans") expects a package name that contains all the entities that needs to be persisted to MONGO, everything else is self understandable here.

CRUD Operations is done using datastore,we will see how it is in action.


We have two entities Address and Employee,Relations between them can be defined as "Referenced" or "Embedded".

Referenced : Here In the below snippet we have @Referenced annotation on attribute "Address" in the employee entity, It tells the mongodb to store the address entity separately in different collection(Table) and store only that address id in the person document.

Embedded : Lets say we have used @Embedded annotation on same attribute "Address",
the complete address document or array of complete address document will be stored inside the person document.

//Address Entity

import org.hibernate.validator.constraints.NotEmpty;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;

@Entity
public class Address {

 public Address() {
  // TODO Auto-generated constructor stub
 }
 
 @Id
 @NotEmpty
 private String doorNo;
 @NotEmpty
 private String Street;
 @NotEmpty
 private String City;
 public String getDoorNo() {
  return doorNo;
 }
 public void setDoorNo(String doorNo) {
  this.doorNo = doorNo;
 }
 public Address(String doorNo, String street, String city) {
  super();
  this.doorNo = doorNo;
  Street = street;
  City = city;
 }
 public String getStreet() {
  return Street;
 }
 @Override
 public String toString() {
  return "Address [doorNo=" + doorNo + ", Street=" + Street + ", City="
    + City + "]";
 }
 public void setStreet(String street) {
  Street = street;
 }
 public String getCity() {
  return City;
 }
 public void setCity(String city) {
  City = city;
 }
 
}


//Employee Entity

import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotEmpty;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Field;
import org.mongodb.morphia.annotations.Index;
import org.mongodb.morphia.annotations.Indexes;
import org.mongodb.morphia.annotations.Reference;
import org.mongodb.morphia.utils.IndexType;

@Entity
@Indexes(   @Index(fields = @Field(value = "name", type = IndexType.TEXT)))     
public class Employee {

 Employee(){
  
 }
 @NotEmpty
 private String name;
 
 @NotEmpty
 private String age;
 
 @NotEmpty
 private String designation;
 
 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }
 @NotNull
 @Reference
 private Address address;
 

 public Employee(String name, String age, String designation,Address address) {
  super();
  this.name = name;
  this.age = age;
  this.designation = designation;
  this.address = address;
 }

 public String getName() {
  return name;
 }



 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 public String getDesignation() {
  return designation;
 }

 @Override
 public String toString() {
  return "Employee [name=" + name + ", age=" + age + ", designation="
    + designation + "]";
 }

 public void setDesignation(String designation) {
  this.designation = designation;
 }
 

}


import java.util.List;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import com.test.beans.Address;
import com.test.beans.Employee;

@Path("/new")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class RestController {
 private Datastore datastore = MongoConnection.getConnection();
 
 
 @GET
 @Path("/employee/{name}")
 public List<Employee> getEmployee(@PathParam("name") String name){
  System.out.println("Name "+name);  
 return datastore.createQuery(Employee.class).
    field("name").equal(name).asList();
   
}
 
 @POST
 @Path("/employee")
 public Employee saveEmployee(@Valid Employee employee){
  System.out.println("Employee is "+employee);
  datastore.save(employee);
  return employee;
  
 }
 
 
 @GET
 @Path("employee/address/{Id}")
 public Address getAddressOnEmployee(@PathParam("Id") String id){
  return datastore.createQuery(Employee.class).field("address").equal(id).get().getAddress();
 }
 
 @DELETE
 @Path("/employee/{name}")
 public int deleteEmployee(@PathParam("name") String name){
  Query<Employee> query = datastore.createQuery(Employee.class).filter("name =", name);
  return datastore.delete(query).getN();
 }
 
 @PUT
 @Path("/employee/{name1}/{name2}")
 public int updateEmployeeName(@PathParam("name1") String name1,@PathParam("name2") String name2){
  Query<Employee> query = datastore.createQuery(Employee.class).filter("name =", name1);
  UpdateOperations<Employee> updateEmployee =  datastore.createUpdateOperations(Employee.class).set("name", name2).set("designation","Chief");
  return datastore.update(query, updateEmployee).getUpdatedCount();
 }
}

As shown in the snippet above, We can do full document operations and also filter the documents based on criteria using morphia.

Download Source Code
Share:

0 comments:

Post a Comment