Hibernate (4.1.2) and Spring (3.1.2) – ManyToMany relationship does not store records in JoinTable

前端 未结 1 1166
孤独总比滥情好
孤独总比滥情好 2021-01-03 15:35

I have a problem and need your help to overcome this issue. Hopefully, this tread may become a reference for similar issues…

In my minimized business model there are

相关标签:
1条回答
  • 2021-01-03 16:11

    The only correct way is the first one:

    @ManyToMany(mappedBy = "users")
    public Set<Title> getTitles() {
        return titles;
    }
    
    ...
    
    @ManyToMany
    @JoinTable(name = "tb_title_user",
               joinColumns = @JoinColumn(name = "title_id"),
               inverseJoinColumns = @JoinColumn(name = "user_id"))
    public Set<User> getUsers() {
        return users;
    }
    

    The inverse side uses the mappedBy attribute to say: "I'm the inverse side. Go see the users attribute in the target entity to see how this association is mapped."

    What you're doing wrong is that you only modify the inverse side in your test. JPA/Hibernate only considers the owner side to know if an association exists. So instead of doing

    user.getTitles().add(title);
    

    you should do

    title.getUsers().add(user);
    

    or even better, do both, to make sure the object graph is coherent.

    I really hope that this tread becomes a reference for similar issues, but I doubt it, because I have already answered this question a gazillion times, and it keeps coming again and again, although it's clearly explained in the documentation:

    If the association is bidirectional, one side has to be the owner and one side has to be the inverse end (ie. it will be ignored when updating the relationship values in the association table):

    [ follows an example with the appropriate annotations on each side of a bidirectional many-to-namy association ]

    0 讨论(0)
提交回复
热议问题