2

This answer explains the functional differences between @ManyToOne and @OneToOne. Still, I don't understand - when would you choose to use @OneToOne?

If I understand correctly, this means every object in table X is mapped to (at most) one object in table Y, and no two X's are mapped to the same Y.

Is the appropriate use case where this is appropriate is optional properties? E.g. Car <--> Trunk, where some cars have a trunk, and if they do, they own it (it's meaningless to talk about a trunk without its car)?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 1
    I'd say the only place I can think of off the top of my head that I have seen this kind of relationship is when storing address information for a person in a separate table then the person. – Danny Dec 15 '11 at 15:19
  • http://stackoverflow.com/questions/6352324/when-we-need-to-use-1-to-1-relationship-in-database-design/6362543#6362543 – Damir Sudarevic Dec 16 '11 at 12:37
  • @DamirSudarevic - voted to close, thanks. – ripper234 Dec 18 '11 at 06:21

2 Answers2

6

Inheritance mapping is a good candidate for one-to-one relations in a database.

Let's say you have a "Person" table to store people working at a company, but a person could be an employee or a contractor. In that case you would store all common attributes in the Person table. For example:

  • Name
  • Address
  • Date of birth
  • ...

Then you define one-to-one relations to the "Employee" and "Contractor" table:

Employee:

  • Payroll number
  • Salary
  • ...

Contractor:

  • Daily rate
  • Contract number
  • ...
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
3

Another reason for 1-1 relationships is to reduce the size of the table record for performance reasons (less wide tables tend to be faster) and when the number of fields needed is so large that the record size would be larger than the actual record size the database can support.

Sometimes there is natural split in the information where the information in the second table is only going to be needed in a few instances where the information in the main table is frequently accessed. In this case it also makes sense to split it up. This is essentually when things fall into two different classes of information but need a one-to-one relationships enforced between them. For instance a car may have only one engine, but you might want to store techincial details about the engine in a diffeernt place than information about the car owner and licensing, etc. because you will use that information differently in the application.

One other place is when you currently have a one-to-one relationship but are planning to make it one to many in the future. Perhaps in a real estate application you start by showing only one picture of the house, but you plan to expand that in your next release.

HLGEM
  • 94,695
  • 15
  • 113
  • 186