views:

112

answers:

5

Say for example I had to entities "Article" and "Tag" (like in a typical blog). Each article can have many tags, and each tag can be used by many articles, so it is a classical m:n relationship.

I need to specify an owning side with JPA. But which side should be the owning side? An article doesn't depend on a certain tag and vice versa. Is there a rule of thumb which side should be the owning side?

A: 

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;
StudiousJoseph
Thank you for the example. But why is the `mappedBy` attribute in the `Tag` class and not in the `Article` class?
deamon
Not an answer to the question.
Willi
+1  A: 

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,

mohammad shamsi
+2  A: 

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.

Pascal Thivent
+1  A: 

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: http://stackoverflow.com/questions/2584521/in-a-bidirectional-jpa-onetomany-manytoone-association-what-is-meant-by-the-inv

Bytecode Ninja
+1  A: 

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.

cdiesse