我正在从事 JPA 项目,我需要你的帮助。
我有两个类,“Person”和“Leader”,它们继承自Person。
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String personId;
}
还有
@Entity
public class Leader extends Person implements Serializable {
private List < Person > listTeam;
public void addPersonInTeam(Person e) {
listTeam.add(e);
}
}
我的问题是,我是否需要在 Leader 类的私有(private)列表 listTeam 之前添加 JPA 注释 @OneToMany 或其他内容?
非常感谢
最佳答案
您需要指定两个类之间的映射,因为对于 Hibernate,关联在这里不相关,您必须在两侧使用注释,我猜您将需要一个 OneToMany
映射:
这是您要搜索的映射:
面对面类(class):
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String personId;
@ManyToOne
@JoinColumn(name="leader_id")
private Leader leader;
//getter and setter
}
在领袖级别:
@Entity
public class Leader extends Person implements Serializable {
@OneToMany(mappedBy = "leader")
private List <Person> listTeam;
//getter and setter
public void addPersonInTeam(Person e) {
listTeam.add(e);
}
}
有关更多信息,您可以查看以下链接:
注意:
我没有在 Person
类中看到字段 personId
的使用,没有必要使用两个不同的 id。
编辑:
回答您的问题:
@JoinColumn(name="leader_id")
不是必需的,但它用于指定外键名称。- 如果关系是
ManyToMany
,则mappedBy
属性用于指定关系的所有者,您可以看到this answer了解更多详情。
关于java - 带有继承的 JPA 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378693/