Spring Data MongoRepository Update

By Arvind Rai, October 17, 2019
This page will walk through how to update entities of collections in Mongo database using MongoRepository interface. The MongoRepository provides save() and saveAll() methods to update the entities. If entities are already available in collection in Mongo database, then they will be updated otherwise they will be inserted as new entities. The save() method updates one entity at a time and returns the updated entity. The saveAll() method updates the given list of entities and returns list of updated entities.
The insert() method of MongoRepository is used to insert new entities and not to update it. If the entity, passed in insert() method, is already available, it will throw error whereas save() method will update that entity.

Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.1.9.RELEASE
3. Spring Data 2.1.10.RELEASE
4. Spring Boot 2.1.7.RELEASE
5. MongoDB Server 4.0
6. Maven 3.5.2

Using save()

The save() method is available in CrudRepository interface with following syntax.
S save(S entity) 
MongoRepository interface extends CrudRepository and hence we can use save() method in MongoRepository. The implementation class of save() method either inserts the entity or updates the entity. The save() method works as following.
1. If the entity with the given id is not available in collection in Mongo database, then save() will work same as insert method of MongoRepository and inserts the entity.
2. If the entity with the given id is already there in collection in Mongo database, then save() method will update the entity.

Suppose we have a following repository in our application.
@Component
public interface PersonRepository extends MongoRepository<Person, Integer> {

} 
Suppose we have an empty collection person in our Mongo database. Now use save() method to save a person.
Person pm = new Person(101, "Narendra", 65);
Person updatedObj = repository.save(pm); 
Entity will be inserted in collection because collection was empty.
{ "_id" : 101, "name" : "Narendra", "age" : 65, "_class" : "com.concretepage.entity.Person" } 
Now update the same entity.
pm.setName("Narendra Modi");
pm.setAge(70);
updatedObj = repository.save(pm); 
Entity will be updated in collection.
{ "_id" : 101, "name" : "Narendra Modi", "age" : 70, "_class" : "com.concretepage.entity.Person" } 

Using saveAll()

The saveAll() is the method of MongoRepository with following syntax.
List<S> saveAll(Iterable<S> entities) 
The list of entities passed in saveAll() will be either inserted or updated. If entity id matches with any existing entity, then that entity will be updated otherwise it will be inserted as new entity.

Suppose we have following entities in person collection.
{ "_id" : 101, "name" : "Lakshmi", "age" : 22, "_class" : "com.concretepage.entity.Person" }
{ "_id" : 102, "name" : "Parvati", "age" : 23, "_class" : "com.concretepage.entity.Person" }
{ "_id" : 103, "name" : "Saraswati", "age" : 24, "_class" : "com.concretepage.entity.Person" } 
Update all these entities using saveAll() method.
Person p1 = new Person(101, "Shri Lakshmi", 30);
Person p2 = new Person(102, "Shri Parvati", 35);
Person p3 = new Person(103, "Shri Saraswati", 40);
List<Person> list1 = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);

List<Person> updatedObj = repository.saveAll(list); 
The updated collection will be as following.
{ "_id" : 101, "name" : "Shri Lakshmi", "age" : 30, "_class" : "com.concretepage.entity.Person" }
{ "_id" : 102, "name" : "Shri Parvati", "age" : 35, "_class" : "com.concretepage.entity.Person" }
{ "_id" : 103, "name" : "Shri Saraswati", "age" : 40, "_class" : "com.concretepage.entity.Person" } 
Find the print screen.
Spring Data MongoRepository Update

Complete Example

pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.7.RELEASE</version>
	<relativePath />
</parent>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-mongodb</artifactId>
	</dependency>
</dependencies> 
MongoDBConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@EnableMongoRepositories(basePackages = "com.concretepage.repository")
public class MongoDBConfig extends AbstractMongoConfiguration {
	@Override
	public String getDatabaseName() {
		return "myMongoDB";
	}
	@Override
	@Bean
	public MongoClient mongoClient() {
		ServerAddress address = new ServerAddress("127.0.0.1", 27017);
		MongoCredential credential = MongoCredential.createCredential("mdbUser", getDatabaseName(), "cp".toCharArray());
		MongoClientOptions options = new MongoClientOptions.Builder().build();
        
		MongoClient client = new MongoClient(address, credential, options);
		return client;
	}
} 
Person.java
package com.concretepage.entity;
import org.springframework.data.annotation.Id;
public class Person { 
	@Id
	private Integer id;
	private String name;
	private Integer age;
	public Person(Integer id, String name, Integer age){
		this.id = id;
		this.name=name;
		this.age=age;
	}
        //Setters and Getters
} 
PersonRepository.java
package com.concretepage.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;
import com.concretepage.entity.Person;

@Component
public interface PersonRepository extends MongoRepository<Person, Integer> {

} 
SaveTest.java
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.config.MongoDBConfig;
import com.concretepage.entity.Person;
import com.concretepage.repository.PersonRepository;

public class SaveTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MongoDBConfig.class);
		ctx.refresh();
		PersonRepository repository = ctx.getBean(PersonRepository.class);

		repository.deleteAll();

		Person pm = new Person(101, "Narendra", 65);
		Person updatedObj = repository.save(pm);
		System.out.println(updatedObj.getName() + " - " + updatedObj.getAge());
		
		pm.setName("Narendra Modi");
		pm.setAge(70);
		updatedObj = repository.save(pm);
		System.out.println(updatedObj.getName() + " - " + updatedObj.getAge());
		
		ctx.registerShutdownHook();
		ctx.close();
	}
} 
Output
Narendra - 65
Narendra Modi - 70 
SaveAllTest.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.config.MongoDBConfig;
import com.concretepage.entity.Person;
import com.concretepage.repository.PersonRepository;

public class SaveAllTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MongoDBConfig.class);
		ctx.refresh();
		PersonRepository repository = ctx.getBean(PersonRepository.class);

		repository.deleteAll();

		Person p1 = new Person(101, "Lakshmi", 22);
		Person p2 = new Person(102, "Parvati", 23);
		Person p3 = new Person(103, "Saraswati", 24);
		List<Person> list1 = new ArrayList<>();
		list1.add(p1);
		list1.add(p2);
		list1.add(p3);
		
		List<Person> updatedObj = repository.saveAll(list1);
		updatedObj.forEach(std -> System.out.println(std.getName() + " - " + std.getAge()));
		
		//Update the persons
		p1.setName("Shri Lakshmi");
		p1.setAge(30);
		p2.setName("Shri Parvati");
		p2.setAge(35);
		p3.setName("Shri Saraswati");
		p3.setAge(40);
		List<Person> list2 = new ArrayList<>();
		list2.add(p1);
		list2.add(p2);
		list2.add(p3);
		
                System.out.println("--- After update ---");
        
		updatedObj = repository.saveAll(list1);
		updatedObj.forEach(std -> System.out.println(std.getName() + " - " + std.getAge()));        

		ctx.registerShutdownHook();
		ctx.close();
	}
} 
Output
Lakshmi - 22
Parvati - 23
Saraswati - 24
--- After update ---
Shri Lakshmi - 30
Shri Parvati - 35
Shri Saraswati - 40 

References

Spring doc: MongoRepository
Spring Data MongoDB - Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us