简体   繁体   中英

How to establish relationship with same entity using JPA, Hibernate

I am trying to create relationships between different persons but couldn't find a way on how to do it using JPA. Below is the model given to support the requirement:

Person table:
Id FirstName LastName
1 John Heller
2 Joseph Heller
3 Andrew Heller
4 Steven Heller

Person_Relationship table
Id Person1 Person2 Relationship
1 1 2 Parent
2 2 1 Child
3 1 3 Sibling
4 3 1 Sibling
5 4 1 Secretary

Can someone please share your experience if you have ever implemented the above using Hibernate as JPA provider.

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

The easiest way is to use a OneToMany association between a Person entity and a RelationShip entity, each entity mapping the associated table:

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());
            }
        }
    }

    ...
}

Try this.

@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 {}

Using this will let Hibernate (JPA) do the hard work of discriminating between the different types of relationship.

If only real life were this easy! ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM