The best way to use the @ManyToMany annotation with JPA and Hibernate

(Last Updated On: January 4, 2018)

Introduction

As simple as JPA annotations might be, it’s not always obvious how efficient they are behind the scenes. In this article, I’m going to show you what is the best way to use the JPA @ManyToMany annotation when using Hibernate.

Domain Model

Assuming we have the following database tables:

A typical many-to-many database association includes two parent tables which are linked through a third one containing two Foreign Keys referencing the parent tables.

Using java.util.List

The first choice for many Java developers is to use a java.util.List for Collections that don’t entail any specific ordering.

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    public Post() {}

    public Post(String title) {
        this.title = title;
    }

    @ManyToMany(cascade = { 
        CascadeType.PERSIST, 
        CascadeType.MERGE
    })
    @JoinTable(name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();

    //Getters and setters ommitted for brevity

    public void addTag(Tag tag) {
        tags.add(tag);
        tag.getPosts().add(this);
    }

    public void removeTag(Tag tag) {
        tags.remove(tag);
        tag.getPosts().remove(this);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Post)) return false;
        return id != null && id.equals(((Post) o).id);
    }

    @Override
    public int hashCode() {
        return 31;
    }
}

@Entity(name = "Tag")
@Table(name = "tag")
public class Tag {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String name;

    @ManyToMany(mappedBy = "tags")
    private List<Post> posts = new ArrayList<>();

    public Tag() {}

    public Tag(String name) {
        this.name = name;
    }

    //Getters and setters ommitted for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Tag tag = (Tag) o;
        return Objects.equals(name, tag.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
} 

There are several aspects to note on the aforementioned mapping that are worth explaining:

  1. The tags association in the Post entity only defines the PERSIST and MERGE cascade types. As explained in this article, the REMOVE entity state transition doesn’t make any sense for a @ManyToMany JPA association since it could trigger a chain deletion that would ultimately wipe both sides of the association.
  2. As explained in this article, the add/remove utility methods are mandatory if you use bidirectional associations so that you can make sure that both sides of the association are in sync.
  3. The Post entity uses the entity identifier for equality since it lacks any unique business key. As explained in this article, you can use the entity identifier for equality as long as you make sure that it stays consistent across all entity state transitions.
  4. The Tag entity has a unique business key which is marked with the Hibernate-specific @NaturalId annotation. When that’s the case, the unique business key is the best candidate for equality checks.
  5. The mappedBy attribute of the posts association in the Tag entity marks that, in this bidirectional relationship, the Post entity own the association. This is needed since only one side can own a relationship, and changes are only propagated to the database from this particular side.

For more details about the @NaturalId annotation, check out this article.

Although the mapping is correct from a JPA perspective, from a database perspective, it’s not efficient at all. To understand why it is so, you need to log and analyze the automated generated SQL statements.

Considering we have the following entities:

final Long postId = doInJPA(entityManager -> {
    Post post1 = new Post("JPA with Hibernate");
    Post post2 = new Post("Native Hibernate");

    Tag tag1 = new Tag("Java");
    Tag tag2 = new Tag("Hibernate");

    post1.addTag(tag1);
    post1.addTag(tag2);

    post2.addTag(tag1);

    entityManager.persist(post1);
    entityManager.persist(post2);

    return post1.id;
});

When removing a Tag entity from a Post:

doInJPA(entityManager -> {
    Tag tag1 = new Tag("Java");
    Post post1 = entityManager.find(Post.class, postId);
    post1.removeTag(tag1);
});

Hibernate generates the following SQL statements:

SELECT p.id AS id1_0_0_,
       t.id AS id1_2_1_,
       p.title AS title2_0_0_,
       t.name AS name2_2_1_,
       pt.post_id AS post_id1_1_0__,
       pt.tag_id AS tag_id2_1_0__
FROM   post p
INNER JOIN 
       post_tag pt 
ON     p.id = pt.post_id
INNER JOIN 
       tag t 
ON     pt.tag_id = t.id
WHERE  p.id = 1

DELETE FROM post_tag
WHERE  post_id = 1

INSERT INTO post_tag
       ( post_id, tag_id )
VALUES ( 1, 3 )

So, instead of deleting just one post_tag entry, Hibernate removes all post_tag rows associated to the given post_id and reinserts the remaining ones back afterward. This is not efficient at all because it’s extra work for the database, especially for recreating indexes associated with the underlying Foreign Keys.

For this reason, it’s not a good idea to use the java.util.List for @ManyToMany JPA associations.

Using java.util.Set

Instead of a List, we can use a Set.

The Post entity tags association will be changed as follows:

@ManyToMany(cascade = { 
    CascadeType.PERSIST, 
    CascadeType.MERGE
})
@JoinTable(name = "post_tag",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private Set<Tag> tags = new HashSet<>();

And the Tag entity will undergo the same modification:

@ManyToMany(mappedBy = "tags")
private Set<Post> posts = new HashSet<>();

If you worry about the lack of a predefined entry order, then you can use either the @OrderBy or @OrderColumn JPA annotations.

@OrderBy does the sorting in-memory, after the entries are fetched from the database while @OrderColumn materializes the element order in a dedicated column that is stored in the post_tag link table.

Now, when rerunning the previous test case, Hibernate generates the following SQL statements:

SELECT p.id AS id1_0_0_,
       t.id AS id1_2_1_,
       p.title AS title2_0_0_,
       t.name AS name2_2_1_,
       pt.post_id AS post_id1_1_0__,
       pt.tag_id AS tag_id2_1_0__
FROM   post p
INNER JOIN 
       post_tag pt 
ON     p.id = pt.post_id
INNER JOIN 
       tag t 
ON     pt.tag_id = t.id
WHERE  p.id = 1

DELETE FROM post_tag
WHERE  post_id = 1 AND tag_id = 3

Much better! There is only one DELETE statement executed which removes the associated post_tag entry.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

Using JPA and Hibernate is very convenient since it can boost developer productivity. However, this does not mean that you have to sacrifice application performance.

By choosing the right mappings and data access pattern, you can make the difference between an application that barely crawls and one that runs at warp speed.

So, when using the @ManyToMany annotation, always use a java.util.Set and avoid the java.util.List.

Subscribe to our Newsletter

* indicates required
10 000 readers have found this blog worth following!

If you subscribe to my newsletter, you'll get:
  • A free sample of my Video Course about running Integration tests at warp-speed using Docker and tmpfs
  • 3 chapters from my book, High-Performance Java Persistence, 
  • a 10% discount coupon for my book. 
Get the most out of your persistence layer!

Advertisements

19 thoughts on “The best way to use the @ManyToMany annotation with JPA and Hibernate

  1. Why does this magic happen? For List it does not function well and suddenly by putting the Set it starts working better.

  2. Hi, Vladmihalcea,

    Thanks for your post.

    I want to allow users to add any custom tags that does not exist in DB.
    In this situation there are no ID’s for tags in request model and also there is a unique constraint for ‘tag name’.
    When I send model like below twice, I get ‘Duplicate entry’ exception because the tags are already exist in DB.

    I can check tags from DB and set it with ID’s if they exist so hibernate does not try to persist it again.

    But are there any way to handle this situation in JPA/Hibernate level.

    {
    “id”: 1,
    “title”:”Test Blog Title6666″,
    “tags”:[
    {“name”: “Tag-1”},
    {“name”: “Tag-2”},
    {“name”: “Tag-3”},
    {“name”: “Tag-4”}
    ]
    }

    Thanks

  3. many thanks for your great article,

    i would to ask , what the benefit from add @JoinTable when we use mappedBy ?

    1. Check out the Relationship module of my High-Performance Java Persistence video course. Not only that you’ll find the answer to your question, but you are going to learn other useful tricks as well.

  4. Hi Vlad,
    I Implemented the association following your suggestion in your book (one-to-many alternative), but I am getting the following error when I try to save the parent entity (Post):
    java.lang.IllegalStateException: persistence context reported no row snapshot for [com.package.PostTag#com.Package.PostTagId@7ae9]
    Any idea why this might be happening?

  5. Hi Vlad,
    First of all, thank you for the great blog!
    Quick question:
    What is the best approach to mapping entities if I have two lists on Post? For example:

    public class Post {
    ...
    private List activeTags = new ArrayList&lt;&gt;();
    private List removedTags = new ArrayList&lt;&gt;();
    ...
    }
    

    What to do with Tag entity? How to map Post entity to Tag?

    Thank you

  6. Hi Vlad,

    If you want to use @OrderColumn as you suggest, I guess it’s better to map the collection to a SortedSet, using a TreeSet as implementation, right ?
    Then, you will need to implement Comparable in your entities and I find this a little confusing, on what should you do the comparison ?

    1. Nope. The OrderColumn makes sense for Lists since you want to preserve the ordering being given by the SQL ORDER BY clause. If you use a SortedSet, then you just need to do the ordering inside the JVM using Comparable, not on the DB side.

      1. Hi Vlad,

        So I guess if you want to use OrderColumn and therefore need to use a List then you need to take the hit of the less performant database operations. I suspect though that this is not avoidable in any case as the order column fields will need to updated accordingly, yes?

      2. You could use @OrderBy as long as you have a column to give you the order (e.g. creation timestamp).

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.