In the past post, we had learned how to work with MongoDB by MongoOperations which supports a set of standard APIs to manipulate data. So in the tutorial, JavaSampleApproach will show a powerful tool SpringData MongoRepository with flexible and more complex APIs to interact with MongoDB.
Related articles:
– Spring MongoOperations to access MongoDB
– How to build SpringBoot MongoDb RestfulApi
– SpringData MongoDB GridFsTemplate to save, retrieve, delete binary files (Image, Text files)
– Angular 4 + Spring Boot + MongoDB CRUD example
– Spring Boot + Angular 6 example | Spring Data + REST + MongoDb CRUD example
Contents
I. Technologies
– Java: 1.8
– Maven: 3.3.9
– Spring Tool Suite: Version 3.8.4.RELEASE
– Spring Boot: 1.5.4.RELEASE
– MongoDB: v3.4.1
I. MongoRepository
MongoRepository is implemented with lots of APIs to store and retrieve data. We can use MongoRepository with full generic CRUD operations of CrudRepository interface, and additional methods of PagingAndSortingRepository interface for pagination and sorting.
MongoRepository also extends QueryByExampleExecutor so it allows execution of Query by Example.
public interface MongoRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> { ... public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { |
-> With a strong set of APIs, We should start Spring MongoRepository to manipulate data from MongoDB.
II. Practice
We create a SpringBoot project that uses MongoRepository to store and retrieve data from MongoDB.
Step to do:
– Create SpringBoot project
– Create Customer document
– Implement Customer MongoRepository
– Implement Client
– Deployment
1. Create SpringBoot project
Using Spring Tool Suite to create a Spring Starter Project, then add dependency {data-mongodb}:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> |
2. Create Customer document
Create a simple Customer document:
package com.javasampleapproach.datamongodb.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="customer") public class Customer { @Id private String id; private String name; private int age; public Customer(String name, int age){ this.name = name; this.age = age; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setAge(int age){ this.age = age; } public int getAge(){ return this.age; } public String toString(){ String info = String.format("{'id': %s 'name': %s, 'age': %d}", id, name, age); return info; } } |
– @Document
: identifies a domain object to persisted to MongoDB
– @Id
: demarcates an identifier.
3. Implement Customer MongoRepository
– interface CustomerMongoRepository extends MongoRepository
package com.javasampleapproach.datamongodb.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import com.javasampleapproach.datamongodb.model.Customer; public interface CustomerMongoRepository extends MongoRepository<Customer, String>{ List<Customer> findByName(String name); } |
– Open application.properties, add configuration to connect with Mongo Server:
spring.data.mongodb.database=jsa_mongodb spring.data.mongodb.port=27017 |
4. Implement Client
Use CommandLineRunner
to implement a simple client to manipulate data from MongoDB via CustomerMongoRepository
:
– customerRepo.save()
– customerRepo.findByName()
– customerRepo.delete()
– customerRepo.findAll()
package com.javasampleapproach.datamongodb; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.javasampleapproach.datamongodb.model.Customer; import com.javasampleapproach.datamongodb.repository.CustomerMongoRepository; @SpringBootApplication public class SpringDataMongoDbApplication implements CommandLineRunner{ @Autowired CustomerMongoRepository customerRepo; public static void main(String[] args) { SpringApplication.run(SpringDataMongoDbApplication.class, args); } @Override public void run(String... arg0) throws Exception { /** * Save Entities */ System.out.println("----------------Save customers!"); // save an Entity Customer peter = new Customer("Peter", 24); customerRepo.save(peter); // save a List Entity List<Customer> custs = Arrays.asList(new Customer("Mary", 27), new Customer("Lauren", 21), new Customer("Peter", 19)); customerRepo.save(custs); /** * Find Entities */ System.out.println("----------------Find customers has name is 'Peter'!"); List<Customer> peters = customerRepo.findByName("Peter"); // -> Show result peters.forEach(System.out::println); /** * Update an Entity */ System.out.println("----------------Rename a customer which has name is 'Peter' to 'Jack'!"); Customer jack = peters.get(0); jack.setName("Jack"); customerRepo.save(jack); /** * Delete an Entity */ System.out.println("----------------Delete the remain Peter customer!"); customerRepo.delete(peters.get(1)); /** * Find All customer */ System.out.println("----------------Show All Customers!"); List<Customer> customers = customerRepo.findAll(); customers.forEach(System.out::println); } } |
5. Deployment
Start MongoDB server by commandline: .\MongoDB\Server\3.4\bin>mongod.exe
-> Logs:
... 2017-06-15T16:53:29.773+0700 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data' 2017-06-15T16:53:29.776+0700 I NETWORK [thread1] waiting for connections on port 27017 |
Build and Run the SpringBoot project with commandlines: mvn clean install
, mvn spring-boot:run
-> Logs:
----------------Save customers! ----------------Find customers has name is 'Peter'! {'id': 594260d3c3efb42844911a9a 'name': Peter, 'age': 24} {'id': 594260d3c3efb42844911a9d 'name': Peter, 'age': 19} ----------------Rename a customer which has name is 'Peter' to 'Jack'! ----------------Delete the remain Peter customer! ----------------Show All Customers! {'id': 594260d3c3efb42844911a9a 'name': Jack, 'age': 24} {'id': 594260d3c3efb42844911a9b 'name': Mary, 'age': 27} {'id': 594260d3c3efb42844911a9c 'name': Lauren, 'age': 21} |
Run MongoDB shell by commandline: .\MongoDB\Server\3.4\bin>mongo.exe
-> Logs:
MongoDB shell version v3.4.1 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.1 ... |
Results with MongoDB shell:
– show dbs
is used to show all MongoDB databases. -> Having one database jsa_mongodb which is created by the SpringBoot MongoRepository application.
– use jsa_mongodb
is used to select the jsa_mongodb database to work.
– show collections
is used to show all collections in current database. -> We just have one collection: {customer}
– db.customer.find()
is used to query all documents of the collection customer. -> We have 3 customer documents {Jack, Mary, Lauren}
IV. Sourcecode
Last updated on February 6, 2020.
Hi,
Thanks for the wonderful examples,
While implementing this i am getting below error :
The method save(S) in the type CrudRepository is not applicable for the arguments (List)
on customerRepo.save(custs); method because custs is list of customer and it is accepting only customer instance not list of customer.
Could you please help me here.