Difference Between One-to-Many, Many-to-One and Many-to-Many?

后端 未结 8 2050
孤城傲影
孤城傲影 2020-11-28 17:39

Ok so this is probably a trivial question but I\'m having trouble visualizing and understanding the differences and when to use each. I\'m also a little unclear as to how co

8条回答
  •  生来不讨喜
    2020-11-28 18:07

    First of all, read all the fine print. Note that NHibernate (thus, I assume, Hibernate as well) relational mapping has a funny correspondance with DB and object graph mapping. For example, one-to-one relationships are often implemented as a many-to-one relationship.

    Second, before we can tell you how you should write your O/R map, we have to see your DB as well. In particular, can a single Skill be possesses by multiple people? If so, you have a many-to-many relationship; otherwise, it's many-to-one.

    Third, I prefer not to implement many-to-many relationships directly, but instead model the "join table" in your domain model--i.e., treat it as an entity, like this:

    class PersonSkill 
    {
        Person person;
        Skill skill;    
    }
    

    Then do you see what you have? You have two one-to-many relationships. (In this case, Person may have a collection of PersonSkills, but would not have a collection of Skills.) However, some will prefer to use many-to-many relationship (between Person and Skill); this is controversial.

    Fourth, if you do have bidirectional relationships (e.g., not only does Person have a collection of Skills, but also, Skill has a collection of Persons), NHibernate does not enforce bidirectionality in your BL for you; it only understands bidirectionality of the relationships for persistence purposes.

    Fifth, many-to-one is much easier to use correctly in NHibernate (and I assume Hibernate) than one-to-many (collection mapping).

    Good luck!

提交回复
热议问题