【发布时间】:2021-07-14 14:23:21
【问题描述】:
- 数据库:H2
- 春天,JPA
我有一个名为 Message 的实体,其类型基本上只是一个带有 id 的通用父级:
public class Message {
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval = true)
@NonNull
List<GenericDTO> records;
}
通用DTO:
@Entity
@Inheritance
public class GenericDTO {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@JsonIgnore
private int dto_id;
public String toStringMessage(List<GenericDTO> records){
return "";
}
}
ChildDTO:
@Data
@Builder(toBuilder = true)
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class ChildDTO extends GenericDTO{
// some fields
}
现在,当我尝试保存消息时,记录字段将保存为 GenericDTO 而不是 ChildDTO。
这个问题与H2有关吗?
【问题讨论】:
-
您的列表是
GenericDTO,而不是ChildDTO的列表。因此对于 JPA,它需要存储一个GenericDTO。 -
@M.Deinum 是的,但是 JPA 应该能够处理这种类型的多态性,不是吗?我也有其他
ChildDTOs,这就是GenericDTO的原因。当我保存Message时,我保存的 DTO 是ChildDTO而不是GenericDTO。 -
集合需要具有正确的类型,因为类型将由该类型决定,在本例中为
GenericDTO。GenericDTO也不应该是abstract和@MappedSuperclass而不是@Entity? -
@M.Deinum 如果我使用
@MappedSuperClass我不能在@OneToMany中使用GenericDTO
标签: java hibernate jpa spring-data-jpa h2