JPA:am:n 关系中哪一方应该是拥有方?
举例来说,我有两个实体:Article
和 Tag
(就像在典型的博客中一样)。每篇文章可以有多个标签,每个标签又可以被多篇文章使用,因此是经典的 m:n 关系。
我需要使用 JPA 指定拥有方。但哪一方应该是拥有一方呢?一篇文章不依赖于某个标签,反之亦然。是否有经验法则来确定哪一方应该是拥有一方?
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 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 for determining which side should be the owning side?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
每个双向关系都需要 JPA 中的拥有方。在
ManyToMany
的特定情况下:@JoinTable
在关系的拥有方指定。来自 JPA 规范:
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.From the JPA specification:
您可以通过考虑希望更新关联的位置来选择拥有方。您只能在一个地方(拥有方)更新多对多关联。因此,选择取决于您想要如何管理/更新关联字段。
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.
我的观点:
这取决于你的业务。哪个实体在您的业务中更重要。
在你的例子中,我认为文章应该是拥有方,
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,
另外值得一提的是,在 JPA 中,拥有方并不意味着包含方或拥有其他实体的一方。有关此内容的更多信息,请参见:在双向 JPA OneToMany/ManyToOne 关联,“关联的反面”是什么意思?
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"?
每当存在 M:N 映射(即存在双向映射)时,我们都会在代码中使用 @ManyToMany 和 @JoinTable 。
要回答“哪一方应该拥有关系”这个问题,请回到您创建的模型以及数据应如何存储在数据库中。
通常,更改仅从关系的所有者端传播到数据库。让我按照你的例子解释一下,
有两个表/模型/POJO,
Article
和Tag
。每当发布
帖子
时,都会与标签
建立关系。或者,每当出版
图书
时,都会与作者
建立关系。因此,在您的情况下,
@JoinColumn
应该放在Post
中。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
andTag
.Whenever a
Post
is posted, a relation with theTags
is made.Or, Whenever a
Book
is published, a relation with theAuthor
is made.So, the
@JoinColumn
should go inPost
in your case.在 MHO 中,这是需要
@ManyToMany
关系的典型情况。如果您使用连接表,您可以在您的文章类中包含类似的内容。
然后在你的 Tag 类中
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.
Then in your Tag class