3

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;
    }
}
nofunatall
  • 561
  • 6
  • 20
  • Are you using Morphia or just the pure Java driver? @BsonCreator is part of the driver, but you've added the [morphia] keyword. – Nic Cottrell Jun 04 '18 at 09:29

2 Answers2

2

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.

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
  • 1
    Thank you for the answer. My problem was that i didn't realize which annotations are part of which library so i was mixing the ones from Morhpia with Spring data and the mongo driver. This was a non issue when i moved to Spring data's mapping annotation @Document as it doesn't seem to need an annotation as long as i created a private, seemingly useless, no param constructor for an immutable multi param object. – nofunatall Sep 25 '18 at 00:37
0

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.

rhewid
  • 21
  • 6
  • 1
    Adding a default constructor definitely works and is a usable workaround, however it feels messy. The developers seem to have provided `@BsonCreator` specifically for this purpose yet the documentation and examples seem to be lacking. – nofunatall Mar 20 '18 at 20:32