Priya Lorha
Priya Lorha

Reputation: 1

I am trying to achieve polymorphic field for my mongo using spring JPA

here is my Value Class @Data


@NoArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        property = TYPE,
        include = JsonTypeInfo.As.EXISTING_PROPERTY,

        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = StaticValue.class, name=STATIC),
        @JsonSubTypes.Type(value = StaticIntValue.class, name=STATIC_INT),
        @JsonSubTypes.Type(value = DynamicDay.class, name = DATE_DYNAMIC),
        @JsonSubTypes.Type(value = PercentageValue.class, name = PERCENTAGE),
        @JsonSubTypes.Type(value = StaticBooleanValueParent.class, name = STATIC_BOOLEAN),
})
@EqualsAndHashCode
@ToString
@JsonSerialize(using = ValueSerializer.class)
@TypeAlias("VALUE")
public abstract class Value {

    @Getter
    @Setter
    @Field(name = MongoConstants.TYPE)
    @JsonProperty("@type")
    private MongoConstants.ValueType type;

    @Field(name = MongoConstants.COMPARE_WITH_PREVIOUS)
    private boolean compareWithPrevious;

    public Value(MongoConstants.ValueType type, boolean compareWithPrevious) {
        this.type = type;
        this.compareWithPrevious = compareWithPrevious;
    }

}




@Data
@ToString(callSuper = true)
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
//@JsonTypeName("PERCENTAGE")
@TypeAlias("PercentageValue")
@NoArgsConstructor
@Document
public class PercentageValue extends Value {

    @NotNull
    private float percentage;

    @JsonCreator
    public PercentageValue(@JsonProperty("type") String type,
                           @JsonProperty("percentage") float percentage,
                                 @JsonProperty("compareWithPrevious") boolean compareWithPrevious) {
        super(MongoConstants.ValueType.PERCENTAGE, compareWithPrevious);  // Fix here
        this.percentage = percentage;
    }
}


Even after this , JPA is trying to create object for Value and is not using type {"value": { "type": "PERCENTAGE", "compareWithPrevious": false, "percentage": 53 } while querying this collection ````public interface ValueRepository extends MongoRepository <Value, String>getting error "Failed to instantiate com.myproject.database.mongo.entities.Value using constructor public com.myproject.database.mongo.entities.Value() with arguments "

I have tried adding objectMapper, custom convertor, serializer, deserializer. Every possible solution chatGPT could give

Upvotes: 0

Views: 12

Answers (0)

Related Questions