我的模型(示例)如下:

CREATE TABLE person (
  id INT PRIMARY KEY,
  name TEXT
  ...
);

CREATE TABLE team (
  id INT PRIMARY KEY,
  name TEXT
  ....
);

CREATE TABLE team_reference_persons (
  team_id INT NOT NULL,
  person_id INT NOT NULL,
  uses_telephone BOOLEAN,
  PRIMARY KEY (team_id, person_id),
  FOREIGN KEY (team_id) REFERENCES team(id),
  FOREIGN KEY (person_id) REFERENCES person(id)
);


而我的JPA定义:

@Entity
@Table(name = "team")
public class Team {
    @Id
    private Integer id;

    @OneToMany
    @JoinTable(name = "team_reference_persons", joinColumns = @JoinColumn(name = "team_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id"))
    private List<Person> teamReferencePersons;
    ...
}

@Entity
@Table(name = "person")
public class Person {
    @Id
    private UUID id;
    private String name;
    ...
}


到目前为止,一切都很好,您所需要的只是团队中的人员清单。但是,现在我需要在个人域中的联接表中添加team_reference_persons.uses_telephone属性,因此我正在寻找一种在创建新的子类时保持个人逻辑的方法。

private class TeamIndividual extends Person {
    boolean uses_telephone;
}


然后通过List<Person>更改Team实体上的List<TeamIndividual>。有可能吗?应该以一种明智的方式指示JPA,以便将连接表属性添加到最终目标实体(在读取和保存时)。

最佳答案

无需将TeamIndividual扩展到Person。
使用@Table(name =“ team_reference_persons”)注释TeamIndividual
在TeamIndividual内部定义字段(teamId,personId,uses_telephone)
用@ManyToOne和@JoinColumn注释字段teamId和PersonId
将列表添加到团队而无需注释
试试这个,它将起作用..!

10-06 10:09