Hibernate最佳实践:避免多对多和“异国情调”的关系 [英] Hibernate Best Practices: Avoiding Many-To-Many and 'exotic' relationships

查看:80
本文介绍了Hibernate最佳实践:避免多对多和“异国情调”的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hibernate最佳实践表明,多对多关联很少见,应该避免。


不要使用外来的关联映射:

真正的多对多关联的实际测试用例很少见。您需要存储在link
表格中的附加信息时,最多
。在这种情况下,将两个一对多
关联用于中间链接类会更好。实际上,大多数协会
是一对多和多对一的。因此,在使用任何其他关联风格时,应谨慎行事

一个基本和常见的情况是:用户可以在多个团队中,一个团队可以有多个成员。



是否有替代方法使用@ManyToMany,除了为连接创建实体表?在团队/成员的情况下,连接表中没有附加数据,因此Team> TeamMembership> User不太实际。

解决方案 div>

使用 @ManyToMany 没有任何内在错误,但在实践中,您很少有机会使用它。通常你需要链接本身的附加属性,在这一点上,这种关系变成了它自己的一个实体。



我的经历中的一个例子是那种人/团队你描述的关系。我首先使用了一个 @ManyToMany ,但是一旦我需要添加一个有效的变量,就必须将它变成一个 @OneToMany 日期关系(人员在特定时间点属于团队)。


The hibernate best practices states that many-to-many associations are rare and should be avoided.

Do not use exotic association mappings:

Practical test cases for real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, most associations are one-to-many and many-to-one. For this reason, you should proceed cautiously when using any other association style.

A basic and common case would be: user can be in more than one team and a team can have more than one member.

Is there an alternative to using @ManyToMany, other than creating an entity for the join table? In the case of team/member, there is no additional data in the join table, so having Team>TeamMembership>User is not so practical.

解决方案

There is nothing intrinsically wrong with using @ManyToMany but in practice, you rarely have the opportunity to use it. Usually you need additional attributes on the link itself, at which point, the relationship becomes an entity of its own.

One example from my experience was the kind of person/team relationship you described. I used a @ManyToMany at first, but had to turn it into a @OneToMany once I needed to add an effective-date on the relationship (person belongs to team at specific point in time).

这篇关于Hibernate最佳实践:避免多对多和“异国情调”的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆