JPA Postgres jsonb collection type with multiple types fails on save

Viewed 143

I will use pets as data model to demonstrate my issue. Pets store has different type of pets. when store created with mix type of pets, i am getting an exception.

[{"type":"cat","sound":"lala","color":"black"},{"type":"dog","bread":"pit","color":"brown"}]";

used by: java.lang.IllegalArgumentException: The given byte array cannot be transformed to Json object ... 134 more Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'cat' as a subtype of com.test.Dog: Class com.test.Cat not subtype of com.test.Dog at [Source: (byte[])" line: 1, column: 119] (through reference chain: java.util.ArrayList[1]) at app//com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)

i understand that postgres having some issue saving object with different types. Is there any way to solve this problem?

entity class:

@Entity
@NoArgsConstructor
@Data
@AllArgsConstructor
@TypeDef(name = "json", typeClass = JsonType.class)
@EntityListeners({
    AuditingEntityListener.class
})
@Audited
public class StoreEntity implements Serializable {

  @Id
  private String id;

  @NotNull
  private String name;
    
   
  @Valid
  @Type(type = "json")
  @Column(columnDefinition = "jsonb")
  private List<Pets> list= new ArrayList<>();

}

data object

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        visible = true,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(name = "cat", value = Cat.class),
        @JsonSubTypes.Type(name = "dog", value = Dog.class),
        @JsonSubTypes.Type(name = "Pig", value = Pig.class)   
})
abstract class Pets {

    private String type;

    @JsonProperty("type")
    private String type;

  
    // getters, setters, toString
}

class Cat extends Pets {  
}

class Dog extends Dogs {
}

Repository
public interface StoreEntityRepository
    extends CrudRepository<StoreEntity, String>, JpaSpecificationExecutor<StoreEntity> {  
}
0 Answers
Related