Thursday, 5 December 2019

Spring boot: MongoDB: save vs insert


save method behaves like below.
save method is used to create or update existing document.

save behaves differently if you pass a document with "_id" parameter.

If a document does not exist with the specified _id value, then save() method creates new document with specified fields in the document.

If a document exists with the specified _id value, then save() method performs an update, replacing all field in the existing record with the fields from the document.

'insert' method behaves like below.
If a document does not exist with the specified _id value, then insert() method performs an insert with the specified fields in the document.

If a document exists with the specified _id value, then insert() method throws an DuplicateKeyException.

Example
Employee emp1 = new Employee("Phalgun", "Garimella");

emp1 = empRepository.save(emp1);

printAllEmployees();

emp1.setFirstName("ram");
emp1.setLastName("Gurram");
System.out.println("\nTrying to insert emp with same id again");

try {
 empRepository.insert(emp1);
} catch (Exception e) {
 e.printStackTrace();
}

// Sleeping to not intervene the error stack with console messages
TimeUnit.SECONDS.sleep(2);

System.out.println("\nTrying to save emp with same id again");
empRepository.save(emp1);

printAllEmployees();

Find the below working application.

Employee.java
package com.sample.app.entity;

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

@Document("employees")
public class Employee {
 @Id
 private String id;

 private String firstName;

 private String lastName;

 public Employee(String firstName, String lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getId() {
  return id;
 }

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

 public String getFirstName() {
  return firstName;
 }

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

 public String getLastName() {
  return lastName;
 }

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

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}


EmployeeRepository.java
package com.sample.app.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.sample.app.entity.Employee;

@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {

}


application.properties
spring.data.mongodb.database=myorg
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

logging.level.org.springframework.data=WARN


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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springDataMongo</groupId>
 <artifactId>springDataMongo</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
 </dependencies>
</project>


App.java
package com.sample.app;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.MongoClient;
import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
 @Value("${spring.data.mongodb.database}")
 private String database;

 @Value("${spring.data.mongodb.host}")
 private String host;

 @Value("${spring.data.mongodb.port}")
 private int port;

 @Autowired
 private EmployeeRepository empRepository;

 public static void main(String[] args) {

  SpringApplication.run(App.class, args);
 }

 public void dropPreviousData() {
  MongoClient mongoClient = new MongoClient(host, port);

  MongoOperations mongoOps = new MongoTemplate(mongoClient, database);

  mongoOps.dropCollection("employees");
 }

 public void printAllEmployees() {
  List<Employee> emps = empRepository.findAll();

  System.out.println("\nAll Employees");
  for (Employee emp : emps) {
   System.out.println(emp);
  }
 }

 @Bean
 public CommandLineRunner demo() {
  return (args) -> {

   dropPreviousData();

   Employee emp1 = new Employee("Phalgun", "Garimella");

   emp1 = empRepository.save(emp1);

   printAllEmployees();

   emp1.setFirstName("ram");
   emp1.setLastName("Gurram");
   System.out.println("\nTrying to insert emp with same id again");

   try {
    empRepository.insert(emp1);
   } catch (Exception e) {
    e.printStackTrace();
   }

   // Sleeping to not intervene the error stack with console messages
   TimeUnit.SECONDS.sleep(2);

   System.out.println("\nTrying to save emp with same id again");
   empRepository.save(emp1);

   printAllEmployees();

  };
 }
}


Total project structure looks like below.


Run App.java, you can see below messages in console.
All Employees
Employee [id=5d52395f5d30d0430498063f, firstName=Phalgun, lastName=Garimella]

Trying to insert emp with same id again
org.springframework.dao.DuplicateKeyException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d52395f5d30d0430498063f') }; nested exception is com.mongodb.MongoWriteException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d52395f5d30d0430498063f') }
 at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:101)
 at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2781)
 at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:547)
 at org.springframework.data.mongodb.core.MongoTemplate.insertDocument(MongoTemplate.java:1436)
 at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:1244)
 at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:1178)
 at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.insert(SimpleMongoRepository.java:244)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
 at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
 at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
 at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
 at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
 at com.sun.proxy.$Proxy48.insert(Unknown Source)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
 at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
 at com.sun.proxy.$Proxy48.insert(Unknown Source)
 at com.sample.app.App.lambda$0(App.java:72)
 at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779)
 at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:763)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:318)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
 at com.sample.app.App.main(App.java:35)
Caused by: com.mongodb.MongoWriteException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d52395f5d30d0430498063f') }
 at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:967)
 at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:494)
 at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:478)
 at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:472)
 at org.springframework.data.mongodb.core.MongoTemplate$6.doInCollection(MongoTemplate.java:1443)
 at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:545)
 ... 42 more

Trying to save emp with same id again

All Employees
Employee [id=5d52395f5d30d0430498063f, firstName=ram, lastName=Gurram]


Previous                                                    Next                                                    Home

2 comments:

  1. I have an "_id" and new feilds are added to the document , now when i perform save(), it is overriding the existing values . I want to update only few fields in the document in such a way that remaining fields should be as it is. How to acheive this and what function is best in this scenario ?

    ReplyDelete
    Replies
    1. For better understanding, https://stackoverflow.com/questions/39001955/spring-data-mongotemplate-save-behaviour

      Delete