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.

public interface MongoRepository
		extends PagingAndSortingRepository, QueryByExampleExecutor {
...
 
 
public interface PagingAndSortingRepository extends CrudRepository {

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


	org.springframework.boot
	spring-boot-starter-data-mongodb

2. Create Customer document

Create a simple Kotlin Customer document:

package com.javasampleapproach.kotlin.mongodb.model

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document

@Document(collection="customer")
class Customer(
	@Id
	var id: String,
	var name: String,
	var age: Int
){
	override fun toString(): String{
		val cust2Str = "{id= ${id}, name = ${name}, age = ${age}}"
		return cust2Str
	}
}

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

3. Implement Customer MongoRepository
package com.javasampleapproach.kotlin.mongodb.repository

import com.javasampleapproach.kotlin.mongodb.model.Customer

import org.springframework.data.mongodb.repository.MongoRepository

interface CustomerMongoRepository: MongoRepository {
	fun findByName(name: String): List
}

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

spring.data.mongodb.database=jsa_mongodb
spring.data.mongodb.port=27017
4. Implement Client
package com.javasampleapproach.kotlin.mongodb

import com.javasampleapproach.kotlin.mongodb.model.Customer
import org.springframework.context.annotation.Bean
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import com.javasampleapproach.kotlin.mongodb.repository.CustomerMongoRepository
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class KotlinSpringDataMongoDbApplication{

	@Bean
	fun imageProcess(customerRepo: CustomerMongoRepository) = CommandLineRunner {
		/**
		 * Save Entities 
		 */
		println("----------------Save customers!")
		// save an Entity
		val peter = Customer("001", "Peter", 24)
		customerRepo.save(peter)
		
		// save a List Entity
		val custs = listOf(Customer("002", "Mary", 27), Customer("003", "Lauren", 21), Customer("004", "Peter", 19))
		customerRepo.save(custs)
		
		/**
		 * Find Entities
		 */
		println("----------------Find customers has name is 'Peter'!")
		val peters = customerRepo.findByName("Peter")
		// -> Show result
		peters.forEach{println(it)}
		
		/**
		 * Update an Entity
		 */
		println("----------------Rename a customer which has name is 'Peter' to 'Jack'!")
		val jack = peters.get(0)
		jack.name = "Jack"
		customerRepo.save(jack)
		
		/**
		 * Delete an Entity
		 */
		println("----------------Delete the remain Peter customer!")
		customerRepo.delete(peters.get(1))
		
		/**
		 * Find All customer
		 */
		println("----------------Show All Customers!")
		val customers = customerRepo.findAll()
		customers.forEach{println(it)}	
	}
}

fun main(args: Array) {
    SpringApplication.run(KotlinSpringDataMongoDbApplication::class.java, *args)
}
5. Deployment

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

-> Logs:

2018-02-11T00:04:10.112-0700 I CONTROL  [initandlisten] MongoDB starting : pid=7976 port=27017 dbpath=D:\data\db\ 64-bit host=LOILE-COMPUTER
2018-02-11T00:04:10.113-0700 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-02-11T00:04:10.116-0700 I CONTROL  [initandlisten] db version v3.4.9

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

-> Logs:

----------------Find customers has name is 'Peter'!
{id= 001, name = Peter, age = 24}
{id= 004, name = Peter, age = 19}
----------------Rename a customer which has name is 'Peter' to 'Jack'!
----------------Delete the remain Peter customer!
----------------Show All Customers!
{id= 001, name = Jack, age = 24}
{id= 002, name = Mary, age = 27}
{id= 003, name = Lauren, age = 21}

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

-> Logs:

MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9

Results with MongoDB shell:

> show dbs
jsa_mongodb  0.000GB
> use jsa_mongodb
switched to db jsa_mongodb
>
> db.customer.find()
{ "_id" : "001", "_class" : "com.javasampleapproach.kotlin.mongodb.model.Customer", "name" : "Jack", "age" : 24 }
{ "_id" : "002", "_class" : "com.javasampleapproach.kotlin.mongodb.model.Customer", "name" : "Mary", "age" : 27 }
{ "_id" : "003", "_class" : "com.javasampleapproach.kotlin.mongodb.model.Customer", "name" : "Lauren", "age" : 21 }
>

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 *

*