【问题标题】:How to establish relationship with same entity using JPA, Hibernate如何使用 JPA、Hibernate 与同一实体建立关系
【发布时间】:2012-02-04 09:47:25
【问题描述】:

我正在尝试在不同的人之间建立关系,但找不到使用 JPA 的方法。以下是支持该要求的模型:

人员表:
身份证 名字 姓氏
1 约翰         海勒
2 约瑟夫      海勒
3 安德鲁      海勒
4 Steven      Heller

Person_Relationship 表
Id Person1 Person2 关系
1 1             2             家长
2 2             1             儿童
3 1             3             兄弟姐妹
4 3             1             兄弟姐妹
5 4             1             秘书

如果您曾经使用 Hibernate 作为 JPA 提供程序实现上述操作,有人可以分享您的经验吗?

【问题讨论】:

  • 这些答案对您有帮助吗?我注意到您没有接受您提出的 4 个问题中的任何一个的答案。当有人给你一个帮助你的答案时,你应该承认。
  • 对不起。我是stackoverflow的新手。从现在开始我会这样做。

标签: java hibernate jpa orm


【解决方案1】:

最简单的方法是在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());
            }
        }
    }

    ...
}

【讨论】:

  • 感谢您的建议,我能够使用这种方法。
【解决方案2】:

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

【讨论】:

  • 鉴于这些表,这远不是使用连接表的标准多对多。
【解决方案3】:

试试这个。

@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) 完成区分不同类型关系的艰苦工作。

要是现实生活这么简单就好了! ;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2019-03-02
    相关资源
    最近更新 更多