nofunatall
nofunatall

Reputation: 561

How to use Mongo Java driver @BsonCreator annotation?

I'm trying to map an immutable object from MongoDB to my Java POJO and i keep getting the following error:

org.springframework.web.util.NestedServletException: 
Request processing failed; 
nested exception is java.lang.RuntimeException: 
org.mongodb.morphia.mapping.MappingException: 
No usable constructor for com.example.model.Item

It seems that when using immutable objects, I need to annotate using @BsonCreator however that doesn't appear to be working and I believe that might be because using this annotation requires me to somehow configure org.bson.codecs.pojo.Conventions#ANNOTATION_CONVENTION. Maybe I'm blind but i can't seem to find any examples anywhere on how to configure this. Any help would be greately appreciated. Here is my annotated POJO:

@Value /* Lombok auto generates getters */
@Builder /* Lombok auto generates builder method */
public class Item implements Serializable {
    private final @NotNull AnEnum type;
    private final int refId;
    private final int quantity;

    @BsonCreator
    public Item(@BsonProperty("type") AnEnum type,
                @BsonProperty("refId") int refId,
                @BsonProperty("quantity") int quantity) {
        this.type = type;
        this.refId = refId;
        this.quantity = quantity;
    }
}

Upvotes: 3

Views: 4860

Answers (2)

Nic Cottrell
Nic Cottrell

Reputation: 9655

This should definitely work with the POJO support. I've just made a test case on github which passes.

I note two issues:

  1. implements Serializable should not be necessary

  2. you will need to specify getters for those 3 fields for the automatic codec builder to pick them up correctly.

Upvotes: 2

rhewid
rhewid

Reputation: 21

try to add an empty constructor, seems that Morphia needs those, at least in my project it helps. Please let me know if it fixed it for you.

Upvotes: 0

Related Questions