Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 815
nofunatall Avatar asked Sep 13 '26 08:09

nofunatall


1 Answers

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.

like image 199
Nic Cottrell Avatar answered Sep 15 '26 23:09

Nic Cottrell



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!