Mongo DB custom conversions in Spring data

Posted by

Context

We stored our data as JSON as below

{
  data: {
    name: "hello",
    project: {
       value: "demo project"
    }
  }
}
@Document(collection = "tasks")
class Task {
    var data: HashMap<String, TaskFieldValue> = HashMap()
}

class TaskFieldValue() {
    var value: String = ""
}

Problems

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [io.nettable.entity.TaskFieldValue]

Solution

@Configuration
class MongoConfiguration {
@Bean
fun customConversions(): MongoCustomConversions {
val converters = ArrayList<Any>()
converters.add(String2NetValue())
return MongoCustomConversions(converters)
}

@ReadingConverter
class String2NetValue : Converter<String, NetTaskFieldValue> {
override fun convert(source: String): NetTaskFieldValue {
val value = NetTaskFieldValue()
value.value = source
return value
}

}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.