Monday, 2 December 2019

Spring boot: MongoDB: insert: Insert new document


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.insert(emp1);

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

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

Find the below working example.

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 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");
 }

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

   dropPreviousData();

   Employee emp1 = new Employee("Phalgun", "Garimella");
  
   emp1 = empRepository.insert(emp1);
   
   emp1.setFirstName("ram");
   emp1.setLastName("Gurram");
   System.out.println("Trying to insert emp with same id again");
   
   try {
    empRepository.insert(emp1);
   }catch(Exception e) {
    e.printStackTrace();
   }
   
   List<Employee> emps = empRepository.findAll();

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

  };
 }
}


Total project structure looks like below.


Run App.java, you can see below messages in console.
Trying to insert emp with same id again
org.springframework.dao.DuplicateKeyException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d5234505d30d0422bdd1f2b') }; nested exception is com.mongodb.MongoWriteException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d5234505d30d0422bdd1f2b') }
 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:60)
 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:34)
Caused by: com.mongodb.MongoWriteException: E11000 duplicate key error collection: myorg.employees index: _id_ dup key: { : ObjectId('5d5234505d30d0422bdd1f2b') }
 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

All Employees
Employee [id=5d5234505d30d0422bdd1f2b, firstName=Phalgun, lastName=Garimella]

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment