Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb and kotlin

I am running into a problem when using spring data mongodb togheter with kotlin. When i try to read objects from mongodb, i get an error complaining that my data classes don't have a default no-args constructor. I can solve this by giving every field a value in my data class, so the compiler will generate a default no-args constructor. Off course i don't really want to do this.

I know there is a jackson kotlin module and it is included in my maven file. It works for deserializing objects that i get over http, so i know that spring picks it up. It seems however that spring data mongodb doesn't use the jackson objectmapper?

Is there a way i can use the jackson objectmapper in spring data mongodb or fix the problem of not having a non args constructor?

like image 969
Geert Olaerts Avatar asked Dec 08 '25 14:12

Geert Olaerts


1 Answers

There is now a No-Arg Plugin. You can add this plugin in you Gradle or Maven Build Script and run your Code without Boilerplate or "Default" Values for your vars.

Very simple example with Gradle:

add Plugin to build.grade

buildscript {
    ext {
        kotlinVersion = '1.1.2'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
    }
}
apply plugin: "kotlin-noarg" // apply "kotlin-jpa" for JPA related annotation
noArg {
    // define annotation, where you need an empty custructor
    annotation("org.springframework.data.mongodb.core.mapping.Document") 
}

Create your Document

@Document(collection = "simpleDoc")
class SimpleDocument(@Id val id: String, @Field val name: String)

Use Spring-Data-REST to create an insert

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/hal+json' -d '{"name":"awesome"}' 'http://localhost:8080/docs'

Read your doc

curl -X GET --header 'Accept: application/hal+json' 'http://localhost:8080/docs/59284d508bc7ee0b4c8fe293'
like image 142
Nik Avatar answered Dec 11 '25 16:12

Nik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!