Customize or provide hints to allow Spring MongoTemplate to deserialize object with final member

final, mongodb, spring, spring-data

Solution

If you want to use non-standard constructor, actually Spring Data MongoDB should be able to pick one automatically, but if it does not happen in your case (you may share more code to make things clear), you can annotate your constructor with @PersistenceConstructor to explicitly tell which constructor should be used.

For something completely non standard, you may want to create custom converter for your class. Read more in Spring Data MongoDB reference

Problem

I am using Spring data's MongoTemplate. I have a class I am successfully saving to mongoDB. When I try to use the find method the retrieve saved objects, I get a NoSuchMethodException because MongoTemplate is trying to call the non-existent default constructor of one of the members of my class. The member has no default constructor because it is a final class with final members. There are two constructors. The first accepts all relevant values as parameters. The second accepts Map and has the @JsonCreator annotation, which enables Jackson to "play nice" with this class. How can I get MongoTemplate to successfully deserialize my class? Is there some sort of annotation that can help? Can I pass MongoTemplate some sort of special deserialization object for handling the relevant class? Can I request MongoTemplate to send parameters as Map the way Jackson does?

Original source