且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一对多、多对一和多对多之间的区别?

更新时间:2021-12-16 09:58:23

一对多:一个人有很多技能,一个技能不会在人之间重复使用

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)

  • 单向:一个人可以通过它的集合直接引用技能
  • 双向:每个子"技能都有一个指向人(未显示在您的代码中)
  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: Each "child" Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many:一个人有很多技能,一个技能在人之间重复使用

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)

  • 单向:一个人可以通过它的集合直接引用技能
  • 双向:一项技能有一组与之相关的人员.
  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: A Skill has a Set of Person(s) which relate to it.

在一对多关系中,一个对象是父",一个是子".父母控制孩子的存在.在多对多中,任何一种类型的存在都依赖于它们之外的某些东西(在更大的应用程序上下文中).

In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).

您的主题(领域)应该决定关系是一对多还是多对多——但是,我发现使关系单向或双向是一个需要牺牲记忆的工程决策,处理、性能等

Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.

令人困惑的是,多对多双向关系不需要对称!也就是说,一群人可以指向一项技能,但该技能不一定只与那些人相关.通常它会,但这种对称性不是必需的.以爱为例——它是双向的(我爱"、爱我"),但通常是不对称的(我爱她,但她不爱我")!

What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!

所有这些都得到了 Hibernate 和 JPA 的良好支持.请记住,在管理双向多对多关系时,Hibernate 或任何其他 ORM 并没有强调保持对称性……这完全取决于应用程序.

All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.