javaspringhibernatemany-to-manybidirectional-relation

Many to many relationship for same type entity


I have an entity as below. I am curious if it is possible to create a relationship as I will be describing with the example:

Here is my service layer code for creating a friendship:

    @Override
    public Person addFriend(String personName, String friendName) 
        throws FriendshipExistsException, PersonNotFoundException {
    Person person = retrieveWithName(personName);
    Person friend = retrieveWithName(friendName);
    if(!person.getFriends().contains(friend)){
        person.getFriends().add(friend);
        return repository.save(person);
    }
    else{
        throw new FriendshipExistsException(personName, friendName);
    }
}

Related Question: N+1 query on bidirectional many to many for same entity type

Updated the source code and this version is working properly.


Solution

  • // Creating a graph to help hibernate to create a query with outer join.
    @NamedEntityGraph(name="graph.Person.friends",
        attributeNodes = @NamedAttributeNode(value = "friends"))
    class Person {}
    
    interface PersonRepository extends JpaRepository<Person, Long> {
        // using the named graph, it will fetch all friends in same query
        @Override
        @EntityGraph(value="graph.Person.friends")
        Person findOne(Long id);
    }
    
    @Override
    public Person addFriend(String personName, String friendName) 
        throws FriendshipExistsException, PersonNotFoundException {
        Person person = retrieveWithName(personName);
        Person friend = retrieveWithName(friendName);
        if(!person.getFriends().contains(friend)){
            person.getFriends().add(friend);
            friend.getFriends().add(person); // need to setup the relation
            return repository.save(person); // only one save method is used, it saves friends with cascade
        } else {
            throw new FriendshipExistsException(personName, friendName);
        }
    

    }

    If you check your hibernate logs, you will see:
    Hibernate: insert into person (name, id) values (?, ?)
    Hibernate: insert into person (name, id) values (?, ?)
    Hibernate: insert into friendship (person_id, friend_id) values (?, ?)
    Hibernate: insert into friendship (person_id, friend_id) values (?, ?)