通过辅助 table 与 Spring 数据映射递归关系

Mapping recursive relation via secondary table with Spring Data

我有这样的数据库:

CREATE TABLE unit
(
    id INTEGER NOT NULL,
    name VARCHAR,
);

CREATE TABLE unit_composition
(
    parent_id INTEGER NOT NULL,
    child_id INTEGER NOT NULL,
    quantity INTEGER,
CONSTRAINT child_fk FOREIGN KEY (parent_id)
        REFERENCES public.refdse (id) MATCH SIMPLE,
CONSTRAINT parent_fk FOREIGN KEY (parent_id)
        REFERENCES public.refdse (id) MATCH SIMPLE
);

ALTER TABLE unit_composition
    ADD CONSTRAINT composit_pk PRIMARY KEY (parent_id, art_nr);

我有 table 个制造单位。每个单元可以有多个子单元,子单元可以有多个子子单元等等。我还有一个数量字段,显示制造单个单元需要多少个子单元。所以这是一种树状关系。

现在我想用 Spring 数据将它映射到 classes。我有一个单元 class,其 ID 和名称为:

@Entity
@Table(name = "unit")
class Unit {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;
...
}

我创建了一个辅助 class 部分:

class Part {
    
    private Unit unit;
    private int quantity;
    ...
}

而且我需要单元 class 来拥有一个像 List subUnits 这样的字段。

我尝试使用@SecondaryTable 和@JoinColumn 注释来完成它,但我收到一条错误消息“关系unit_unit 不存在”。 我还尝试将 Part 设为 @Entity,但它没有 Id 字段。 或者,我尝试制作 @Embeddable class PartId 并将一个实例插入到 Part class 中,如下所示:

@Embeddable
public class PartId implements Serializable {
    
    private Unit parentUnit;
    private Unit unit;

我在 PartId class 中收到一个错误,指出“基本类型不应该是持久性实体”,因为它是可嵌入的并且没有 table 分配给它。

那么我怎样才能使这项工作能够递归地获得给定单元的所有子单元(带有子子单元等)?我不太明白如何映射一个实体,该实体实际上只是从 table 到自身的链接。

所以我的第一个解决方案是创建 Jdbc 模板存储库,并通过 SQL-queries 手动构建必要的列表。但是我发现了更好更简单的解决方案,它需要向 unit_composition table 添加一个 id 列,因此使 Part class 成为一个与 Unit class 具有 @ManyToOne 关系的 @Entity。剩下的就是 Spring Data.