5

In his blog, Ayende suggests that using a one-to-one is probably not the best way to implement a traditional 1:1 object relationship (e.g. customer.Name == name.Customer).

  1. How do I choose when to use the one-to-one relationship?
  2. Why should I choose 2 one-to-many relationships
  3. How does the one-to-one work (There are no FK columns generated)

One to one:

One-to-one

2 many-to-one:

enter image description here

Darbio
  • 11,286
  • 12
  • 60
  • 100
  • Are you sure no FK columns are generated? For me they are generated, and the database looks exacly like it would look with a one-to-many relationship. Maybe you used `Invserse` for both sides by mistake? – Ilya Kogan May 30 '11 at 10:14
  • Yes I am sure - The one-to-one table looks like the entity, with no FK key. – Darbio May 30 '11 at 11:07
  • 2
    There are two ways to do one-to-one. The way you generated it, it uses the primary keys of both entities to join them up. In the second case you have a foreign key with a unique constraint http://nhforge.org/doc/nh/en/index.html#mapping-declaration-onetoone – Vadim May 30 '11 at 20:13
  • 1
    Vadim's comment is an answer to this question. I disagree with Ayende, because he approaches Hibernate design to database design, but not vice versa. My opinion is that database must be designed first without considering which ORM will be used. And one-to-one relationship is useful, because sometimes additional foreign key column seems to be redundant. – meir Jul 14 '11 at 10:04
  • 2
    Thats the difference between you and Ayende, Meir. He is solving the business problem and not worrying about persistence, you're worrying about the persistence first. – Phill Jul 21 '11 at 02:33

1 Answers1

2

Only reason I've come across for using one-to-many mapping is because of performance.

I've initially went with one-to-one until project hit the wall with performance issue. Problem happens because you usually can't have lazy loading for one-to-one mapping on reverse side. E.g. when you have entity A which can (but doesn't have to) have related entity B on that mapping. In that case, for each entity A you load, entity B is also loaded. This is done to prevent error with checking if related object exists. Proxy for lazy loading would mislead you to think that related entity exists, even when it does not. If you check for related entity existence like this you will be in a problem

if (entityA.EntityB == null) HandleNoEntityB();

If you use one-to-many mapping however, lazy loading is no problem, because developer is working with a collection for which we can create proxy.

if (entityA.EntitiesB.Count == 0) HandleNoEntityB();

This doesn't have to be a problem if you can make an assumption in your system that entity A always has exactly one related entity B. In that case, you should set contrained="true" on that mapping.

Nikola Radosavljević
  • 6,871
  • 32
  • 44