JPA 存储库在我的实体中保存错误类型的字段

JPA repository saves the wrong type of a field in my entity

我有一个名为 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有关吗?

默认情况下,jpa 将层次结构的所有实体保存在一个 table 中,其中包含所有可能的实体字段的列。这就是为什么您的 children 被保存到 GENERICDTO table。要将层次结构中每个 class 的实体保存到单独的 table,您需要指定继承策略:

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

我建议您查看这篇文章以获取有关该主题的更多信息:https://www.baeldung.com/hibernate-inheritance

解决方案有点棘手,GenericDTOChildDTO 在不同的项目中,发生的事情是未扫描项目中存在 ChildDTO 的包,因此 spring。添加包扫描解决了我的问题。