springboot JPA中抽象类的OneToMany

问题描述 投票:0回答:1

我遇到了一个问题,当我想获得与抽象类的多对一关系时,它给出了无法实例化它的错误,这是合乎逻辑的。但是我希望它获取父类、cd 或 dvd 的实例。在数据库中,它们也相互链接。我有一个与 CD 和 DVD 表相关的收藏品表。 我有以下类结构:

public class Collection {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "collection", cascade = CascadeType.ALL)
    @JsonManagedReference
    private List<Collectable> collectableList;
}

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Collectable {
    @ManyToOne
    @JoinColumn(name = "collection_id")
    @JsonBackReference
    private Collection collection;
}

@Entity
@Component("Cd")
public class Cd extends Collectable {}

@Entity
@Table(name = "dvd")
@Component(value = "DVD")
public class Dvd extends Collectable {}

知道如何解决这个问题吗?我仍然想将摘要保留在收藏品上,因为我不希望它是可实例化的。

我尝试查看 JPA 的文档和各种其他 Spring Boot 或 JPA 相关源,但无济于事。我还询问了多个人工智能,希望能得到任何想法,但没有得到任何有用的结果。

spring-boot jpa spring-data-jpa
1个回答
0
投票

即使不太喜欢,因为它看起来像是一种解决方法而不是实现 OOP 原则的解决方案,您也可以使用

@DiscriminatorColumn
来映射它们。定义一个列 (collectable_type) 来区分 Cd 和 Dvd 等子类。每个子类都标有
@DiscriminatorValue
以在collectable_type 列中指定其值。此设置使 JPA 能够管理多态配置,从而允许通过 Collection 实体检索 CD 和 DVD。

@Entity
@Table(name = "collectable")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "collectable_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Collectable {
    @ManyToOne
    @JoinColumn(name = "collection_id")
    @JsonBackReference
    private Collection collection;
}

@Entity
@DiscriminatorValue("Cd")
public class Cd extends Collectable {}

@Entity
@DiscriminatorValue("Dvd")
public class Dvd extends Collectable {}

© www.soinside.com 2019 - 2024. All rights reserved.