JPA: which side should be the owning side in a m:n relationship?

后端 未结 6 1929
予麋鹿
予麋鹿 2020-12-30 08:12

Say, for example, I had two entities: Article and Tag (like in a typical blog). Each article can have many tags, and each tag can be used by many a

相关标签:
6条回答
  • 2020-12-30 08:18

    You choose the owning side by considering where you want the association be updated. You can update de ManyToMany association in only one place( the owning side). So the choice depend on how you want to manage/update your association fields.

    0 讨论(0)
  • 2020-12-30 08:23

    In MHO this is a typical case where a @ManyToMany relationship is needed.

    If you use a Join Table, you can have in your Article class something like.

    @ManyToMany 
    @JoinTable(name="TAG_ARTICLE", 
          joinColumns=@JoinColumn(name="ARTICLE_ID"),
          inverseJoinColumns=@JoinColumn(name="TAG_ID"))
    private Collection<Tag> tags;
    

    Then in your Tag class

    @ManyToMany(mappedBy="tags")
    private Collection<Article> articles;
    
    0 讨论(0)
  • 2020-12-30 08:25

    Whenever there is an M:N mapping i.e. there is a bidirectional mapping we use @ManyToMany and @JoinTable in our code.

    To answer this question "Which side should own the relationship" goes back to models you create and how the data should be stored in the database.
    Generally, the changes are only propagated to the database from the owner side of the relationship. Let me explain as per your example,

    There are two tables / models / POJOs, Article and Tag.
    Whenever a Post is posted, a relation with the Tags is made.
    Or, Whenever a Book is published, a relation with the Author is made.
    So, the @JoinColumn should go in Post in your case.

    0 讨论(0)
  • 2020-12-30 08:28

    Every bidirectional relationship requires an owning side in JPA. In the particular case of ManyToMany:

    • @JoinTable is specified on the owning side of the relationship.
      • the owning side is arbitrary, you can pick any of the two entities to be the owner.

    From the JPA specification:

    9.1.26 ManyToMany Annotation

    Every many-to-many association has two sides, the owning side and the non-owning, or inverse, side. The join table is specified on the owning side. If the association is bidirectional, either side may be designated as the owning side.

    0 讨论(0)
  • 2020-12-30 08:31

    my point of view:

    it depends on your business. which entity is more important in your business.

    in your example, i think Article should be owning side,

    0 讨论(0)
  • 2020-12-30 08:34

    Also it worths to mention that in JPA the owning-side does not imply the containing side or the side that owns the other entities. More about this here: In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

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