最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

polymorphism - I am trying to achieve polymorphic field for my mongo using spring JPA - Stack Overflow

programmeradmin1浏览0评论

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;
        thispareWithPrevious = 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

发布评论

评论列表(0)

  1. 暂无评论