Vihung
Vihung

Reputation: 13397

What's the best way to model Friendship using Java Hibernate and JPA

Let's say I have a Person entity.

And a Person can have a 'Friendship' relationship with one or more other Persons.

I would model that with, say, an entry in a table

| Person Id 1 | Person Id 2 |

But, semantically, if Person 1 is friends with Person 2

| Person Id 1 | Person Id 2 |

it is the same as saying Person 2 is friends with Person 1

| Person Id 2 | Person Id 1 |

Of course, there are lots of ways in Java, and in the query, such as ((person1=x AND person2=y) OR (person1=y AND person2=x)) that I would make sure that this equivalence is honoured. But what's a more efficient way to model this in the database itself, and in subsequent Repository, JPQL Queries etc.

To summarise; I want to be able to check whether Person 1 is friends with Person 2, without having two checks - (is Person 1 friends with Person 2) or (is Person 2 friends with Person 1). Idiomatically, I just want to say (are Person 1 and Person 2 friends).

I want to implicitly model the equivalence that is A is friends with B then B is automatically friends with A.

Upvotes: 0

Views: 208

Answers (1)

  • The following person entity class
    @Entity
    public class Person {

    //Id and properties

      @ManyToMany
      @JoinTable(name="friendship", 
                joinColumns={@JoinColumn(name="person_id")}, 
                inverseJoinColumns={@JoinColumn(name="friend_id")})
       private Set<Person> friends = new HashSet<Person>();

       // Getter and Setter methods
     }
  • It will generate a person table and a friendship table. person table will only contain information related to Person and friendship table will only have two columns person_id and friend_id to keep the relationship.

Upvotes: 1

Related Questions