How to use SpringData MongoRepository to interact with MongoDB

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)

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.

-> With a strong set of APIs, We should start Spring MongoRepository to manipulate data from MongoDB.

SpringData Mongodb - architectures c

II. Practice

We create a SpringBoot project that uses MongoRepository to store and retrieve data from MongoDB.

SpringData Mongodb - project structure

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}:

2. Create Customer document

Create a simple Customer document:

@Document: identifies a domain object to persisted to MongoDB
@Id: demarcates an identifier.

3. Implement Customer MongoRepository

interface CustomerMongoRepository extends MongoRepository

– Open, add configuration to connect with Mongo Server:

4. Implement Client

Use CommandLineRunner to implement a simple client to manipulate data from MongoDB via CustomerMongoRepository:

5. Deployment

Start MongoDB server by commandline: .\MongoDB\Server\3.4\bin>mongod.exe

-> Logs:

Build and Run the SpringBoot project with commandlines: mvn clean install, mvn spring-boot:run

-> Logs:

Run MongoDB shell by commandline: .\MongoDB\Server\3.4\bin>mongo.exe

-> Logs:

Results with MongoDB shell:

SpringData Mongodb - Results

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


Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *