【发布时间】:2021-02-16 12:44:45
【问题描述】:
我有这样的数据库:
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);
我有一张制造单位表。每个单元可以有多个子单元,子单元可以有多个子子单元,以此类推。我还有一个数量字段,显示制造单个单元需要多少子单元。所以它是一种树关系。
现在我想用 Spring Data 将它映射到类。我有一个带有 ID 和名称的 Unit 类:
@Entity
@Table(name = "unit")
class Unit {
@Id
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
...
}
我已经创建了一个辅助类 Part:
class Part {
private Unit unit;
private int quantity;
...
}
而且我需要单元类有一个像 List subUnits 这样的字段。
我尝试使用@SecondaryTable 和@JoinColumn 注释来执行此操作,但我收到一条错误消息,提示“Relation unit_unit 不存在”。 我还尝试将 Part 设为 @Entity,但它没有 Id 字段。 或者,我尝试创建 @Embeddable 类 PartId 并将实例插入 Part 类,如下所示:
@Embeddable
public class PartId implements Serializable {
private Unit parentUnit;
private Unit unit;
我在 PartId 类中收到一个错误,提示“基本类型不应该是持久性实体”,因为它是可嵌入的并且没有分配给它的表。
那么我怎样才能使这项工作能够递归地获得给定单元的所有子单元(带有子子单元等)?我不太明白如何映射一个实际上只是从表链接到自身的实体。
【问题讨论】:
标签: java spring jpa orm spring-data