Hibernate Tips: How to map a bidirectional many-to-many association

By Thorben Janssen

Association Mapping, Mapping

Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

My table model contains a many-to-many association. How can I model it with Hibernate so that I can navigate it in both directions?

Solution:

You need to model the association on both entities if you want to be able to navigate it in both directions. Let’s have a look at an example.

Multiple Authors can write multiple books and a book can be written by one or more authors. That’s a typical many-to-many association, and you probably want to navigate it in both directions in your domain model and queries.
You need to model it as a many-to-many association on the Book entity and the Author entity.

BidirectionalManyToMany

Let’s begin with the Book entity which is the owning side of the association in this example. That means that it defines the association and the Author entity just references it.
The relationship definition consists of two mandatory and one optional part. The entity attribute List authors and the @ManyToMany annotation are required. The attribute models the association, and the annotation declares the kind of relationship. The @JoinTable annotation is optional.

It allows you to define the name of the join table and foreign key columns that store the many-to-many association.
I use it in the following code snippet to set the name of the join table to book_author and the names of the foreign key columns to fk_book and fk_author. If you don’t define the name yourself, Hibernate generates default table and column names. The default table name is the combination of both entity names.

In this example, it would be Book_Author. The foreign key column name is generated by combining the name of the association mapping attribute and the name of the primary key attribute of the entity. These would be books_id and authors_id in this example.

You also need to map the many-to-many association on the Author entity to make it bidirectional.
As you can see in the following code snippet, this is done in a similar way as on the Book entity.
You need an attribute that models the association and a @ManyToMany annotation.
In this example, it’s the List books attribute which I annotated with a @ManyToMany annotation. The association is already defined on the Book entity. You can therefore just reference the attribute on the Book entity in the mappedBy attribute and Hibernate will use the same definition.

That’s all you need to do to define a bidirectional many-to-many association. You can now navigate it in both directions in your JPQL or Criteria API queries or on your domain objects.

Bidirectional associations are easy to use in queries, but they also require an additional step when you persist a new entity.
You need to update the association on both sides when you add or remove an entity.
You can see an example of it in the following code snippet in which I first create a new Author entity and add the Book entity to the List of books.
And after that, I also need to add the new Author entity to the List of authors on the Book entity.

Updating the associations on both entities is an error-prone task. It’s, therefore, a good practice to provide helper methods for it.


 

Hibernate Tips Book







Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!



Tags

Association Mapping, Mapping


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Reply

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. Hello!
    I’ve just tried you example, and I’m getting a StackOverflow exception when trying to add a book to list of books in author entity, after adding author to list of authors in book entity.

    So, it suposed to be a bidirectional reference problem.

    How can I solve it?

    1. How do you add the entities to the lists?
      It seems like you implemented a helper method on the Book and the Author entity which call each other. That creates an endless recursion. You need to make sure that your helper methods access the lists directly and that not more than one of them calls the other.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}