3

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?

2
  • That's usually a jackson related issue. Jackson, Hibernate and other tools that create objects for you need the object to declare a no-arg constructor. Actually it makes sense, since the framework don't know anything about the values you want to assign in case of arg-constructors. Your question would be better explained with some sample code, by the way. Commented Nov 26, 2016 at 13:20
  • A bit late, but show me your data class please. I think you are using default values, aren't you? Commented Dec 29, 2016 at 8:39

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.