如何使用JPA、Hibernate和同一实体建立关系



我试图在不同的人之间创建关系,但找不到如何使用JPA来实现这一点的方法。以下是支持该要求的模型:

人员表:
Id名字姓氏
1约翰 nbsp nbsp nbsp nbsp Heller
2 Joseph nbsp nbsp Heller
3安德鲁 nbsp nbsp Heller
4史蒂文 nbsp nbsp Heller

人员关系表
Id Person1 Person2关系
1 1 nbsp nbsp nbsp nbsp nbsp 2 nbsp nbsp nbsp nbsp nbsp nbsp;父级
2 2 nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp nbsp nbsp nbsp nbsp;儿童
3 1 nbsp nbsp nbsp nbsp nbsp 3 nbsp nbsp nbsp nbsp nbsp nbsp;兄弟姐妹
4 3 nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp nbsp nbsp nbsp nbsp;兄弟姐妹
5 4 nbsp nbsp nbsp nbsp nbsp 1 nbsp nbsp nbsp nbsp nbsp nbsp;秘书

如果你曾经使用Hibernate作为JPA提供者实现过上述内容,请有人分享你的经验。

最简单的方法是在Person实体和RelationShip实体之间使用OneToMany关联,每个实体映射关联的表:

public class Person {
    @OneToMany(mappedBy = "person1")
    private List<RelationShip> relationships;
    public List<Person> getSiblings() {
        List<Person> result = new ArrayList<Person>();
        for (RelationShip r : relationShips) {
            if (r.getType() == RelationshipType.SIBLING) {
                result.add(r.getPerson2());
            }
        }
    }
    ...
}

使用可连接的标准多对多关系。

试试这个。

@Entity
public class Person {
    @Id
    private Long id;
    @OneToMany
    Set<Sibling> siblings;
    @OneToMany
    Set<Parent> parents;
    @OneToMany
    Set<Child> children;
    @OneToMany
    Set<Secretary> secretaries;
}
@Entity
@Table(name="person_relationship")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="relationship", discriminatorType=DiscriminatorType.STRING)
public abstract class Relationship {
    @Id
    private Long id;
    @OneToOne
    @JoinColumn(name="person1")
    private Person owner;
    @OneToOne
    @JoinColumn(name="person2")
    private Person related;
}
@Entity
@DiscriminatorValue("Sibling")
public class Sibling extends Relationship {}
@Entity
@DiscriminatorValue("Child")
public class Child extends Relationship {}
@Entity
@DiscriminatorValue("Parent")
public class Parent extends Relationship {}
@Entity
@DiscriminatorValue("Secretary")
public class Secretary extends Relationship {}

使用它可以让Hibernate(JPA)完成区分不同类型关系的艰巨工作。

如果现实生活如此轻松就好了!;-)

最新更新