Kotlin – SpringData MongoRepository to interact with MongoDB

In the tutorial, JavaSampleApproach will show a powerful tool SpringData MongoRepository with flexible and more complex APIs to interact with MongoDB.

I. Technologies

– Kotlin 1.2.20
– Apache Maven 3.5.2
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot – 1.5.10.RELEASE
– MongoDB: v3.4.1

II. 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.

III. Practice

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

Kotlin - Spring Data MongoDB - structure

Step to do
– Create Kotlin SpringBoot project
– Create Customer document
– Implement Customer MongoRepository
– Implement Client
– Deployment

1. Create Kotlin SpringBoot project

Using SpringToolSuite to create a Kotlin Spring Starter Project, then add dependency {data-mongodb}:

2. Create Customer document

Create a simple Kotlin Customer document:

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

3. Implement Customer MongoRepository

– Open application.properties, add configuration to connect with Mongo Server:

4. Implement Client

5. Deployment

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

-> Logs:

Run the SpringBoot project with commandline: mvn spring-boot:run

-> Logs:

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

-> Logs:

Results with MongoDB shell:

IV. Sourcecode

KotlinSpringDataMongoDB

By grokonez | February 11, 2018.



Related Posts


Got Something To Say:

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

*