Spring Data MongoDB Insert document

In this tutorial we will discuss about the inserting document to the mongoDB. Document is same as a row in the table of relational database. In the our example we will insert a document to "dojCollection" of "dineshonjavaDB".

Methods for saving and inserting documents-
There are several convenient methods on MongoTemplate for saving and inserting your objects. To have more fine grained control over the conversion process you can register Spring converters with the MappingMongoConverter,
for example Converter<Employee, DBObject> and Converter<DBObject, Employee>.

Note: The difference between insert and save operations is that a save operation will perform an insert if the object is not already present.
1. save” is means “insert it if record is not exists” and “update it if record is existed”, or simply saveOrUpdate().
2. insert” is means “insert it if record is not exits” and “ignore it if record is existed”.

The simple case of using the save operation is to save a POJO. In this case the collection name will be determined by name (not fully qualfied) of the class. You may also call the save operation with a specific collection name. The collection to store the object can be overridden using mapping metadata.

When inserting or saving, if the Id property is not set, the assumption is that its value will be autogenerated by the database. As such, for autogeneration of an ObjectId to succeed the type of the Id property/field in your class must be either a String, ObjectId, or BigInteger.

In Spring data for MongoDB, you can use save(), insert() and insertList() to save domain object into mongoDB database.
Employee employee = new Employee("...");
 
 //save employee object into "employee" collection
 mongoOperation.save(employee);
 
 //save employee object into "newCollection" collection
 mongoOperation.save("newCollection",employee );
 
 //save employee object into "employee" collection
 mongoOperation.insert(employee);
 
 //save employee object into "newCollection" collection
 mongoOperation.insert("newCollection", employee );
 
 //save list of employee objects into "employee" collection
 mongoOperation.insertList(employeeInList);
 
 //save list of employee objects into "newCollection" collection
 mongoOperation.insertList("newCollection", employeeInList);


The insert/save operations available to you are listed below.
  • void save (Object objectToSave) Save the object to the default collection.
  • void save (Object objectToSave, String collectionName) Save the object to the specified collection.
A similar set of insert operations is listed below
  • void insert (Object objectToSave) Insert the object to the default collection.
  • void insert (Object objectToSave, String collectionName) Insert the object to the specified collection.
  • insertAll Takes a Collection of objects as the first parameter. This method ispects each object and inserts it to the appropriate collection based on the rules specified above.

Note: By default, if you saved an object, and didn’t define any of the "collection name", it will use the domain object name as the collection name. See the "save" method on mongoTemplate.
public void save(Object objectToSave) {
   save(getEntityCollection(objectToSave), objectToSave);
}


See the full example to insert document into the "dojCollection" of the "dineshonjavaDB".

Step 1: Creating the domain class Employee
Employee.java
package com.dineshonjava.mongo.dto;

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

/**
 * @author Dinesh Rajput
 *
 */
@Document(collection = "dojCollection")
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}

Step 2: Creating configuration file
mongo-config.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
  
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
 <mongo:mongo>
  <mongo:options connections-per-host="100"
   threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 </mongo:mongo>
 
 <context:annotation-config/>
     
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
   <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   </bean>
   
</beans>

Step 3: Creating Class which inserting the document into the mongoDB.
HelloMongoDB.java
package com.dineshonjava.mongo.main;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  // Case1 - insert a employee, put "DOJ" as collection name 
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Anamika Rajput");
  employee.setSalary(30000);
  employee.setEmpAge(23);
  
  mongoOperations.save(employee, "DOJ");
     
  // find
  Employee employee1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employee1);
   
  // Case2 - insert a employee, put entity as collection name 
  Employee employee2 = new Employee();
  employee2.setEmpId(1002);
  employee2.setEmpName("Dinesh Rajput");
  employee2.setSalary(70000);
  employee2.setEmpAge(26);
  
  mongoOperations.save(employee2);
     
  // find
  Employee employee3 = mongoOperations.findOne(query(where("empId").is(1002)), Employee.class);
  System.out.println(employee3);
  
  // Case3 - insert a list of employees
  Employee employee4 = new Employee();
  employee4.setEmpId(1003);
  employee4.setEmpName("Adesh Rajput");
  employee4.setSalary(30000);
  employee4.setEmpAge(23);
  
  Employee employee5 = new Employee();
  employee5.setEmpId(1004);
  employee5.setEmpName("Vinesh Rajput");
  employee5.setSalary(32000);
  employee5.setEmpAge(23);
  
  Employee employee6 = new Employee();
  employee6.setEmpId(1005);
  employee6.setEmpName("Sweety Rajput");
  employee6.setSalary(50000);
  employee6.setEmpAge(22);
  
  List<Employee> empList = new ArrayList<Employee>();
  empList.add(employee4);
  empList.add(employee5);
  empList.add(employee6);
 
  mongoOperations.insert(empList, "Employee-List");
 
List<Employee> results = mongoOperations.find(query(where("empAge").is(23)), Employee.class, "Employee-List");
  System.out.println("Results: " + results);
  
 }
}

Step 4: Running the Example
Following code shows how to run this example

HelloMongoTestApp.java
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloMongoTestApp {

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.
output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=30000]
Employee [age=26, empName=Dinesh Rajput, empId=1002, salary=70000]
Results: [Employee [age=23, empName=Adesh Rajput, empId=1003, salary=30000], Employee [age=23, empName=Vinesh Rajput, empId=1004, salary=32000]]
DONE!


Download SourceCode+Libs
MongoDBSpringInsertDemo.zip

References
Spring data for MongoDB


                             <<previous<<             || index  ||         >>next>>


No comments:

Post a Comment