将 parent table 的主键映射到 child table 的外键

mapping primary key of parent table to foreign key of child table

我有一个 parent table,我正在尝试在 parent 和 child table 之间创建一个@OneToMany 关系(例如一个 parent table 可以关联多个 child table).

Parent.java

@Entity
@Table(name = "parent")
public class Threat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long parentId;

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

Child.java

@Entity
@Table(name = "child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long childId;

    @Column(name = "parent_id")
    private long parentId;

    @Column(name = "name")
    private String childName;

    @Column(name = "age")
    private Integer childAge;
}

考虑到我需要将 parent table (parent.id) 的主键加入到 child table 这不是主键 (child.parent_id)。理想情况下,当我 return a Parent object 时,我希望同时显示 parent id 和 children 的列表,因此 parent id 列在 parent 和 children 中。这样,如果 parent 没有 children,我的 object.

中仍然有 parent id

我一直在做一些研究,我想知道我是否应该使用

@PrimaryKeyJoinColumn 

and/or

@Inheritance(strategy = InheritanceType.JOINED)

虽然我还没弄清楚如何实施它们。任何帮助将不胜感激。

结帐@JoinColumn。 来自 Java 文档:

Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

Example:

   @ManyToOne
   @JoinColumn(name="ADDR_ID")
   public Address getAddress() { return address; }

Example: unidirectional one-to-many association using a foreign key mapping

   // In Customer class
   @OneToMany
   @JoinColumn(name="CUST_ID") // join column is in table for Order
   public Set<Order> getOrders() {return orders;}

有了这个,您的实体应该如下所示:

@Entity
@Table(name = "parent")
public class Threat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long parentId;

    @Column(name = "name")
    private String parentName;

    @OneToMany
    @JoinColumn(name="parent_id")
    private List<Child> children = new ArrayList<>();
}

现在无论何时获取 Parent ,您都可以访问关联的子实体。

此外,如果您总是需要在查询父实体时获取子实体,则可以指定 @OneToMany(fetch = FetchType.EAGER)