2

Reading some hibernate documentation, I've stumbled upon this pattern :

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <many-to-one name="address" 
        column="addressId" 
        unique="true"
        not-null="true"/>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
    <one-to-one name="person" 
        property-ref="address"/>
</class>

from jboss hibernate doc

At first glance this seems pretty straightforward. Each Person have one and only one address, and each Address have a person.

But in a DB this pattern would allow an Address to have multiple Person referencing it, how hibernate could resolve this mapping without a list ? How a one-to-one can have a property-ref on a many-to-one field ? I think it should only be possible to have many-to-one <=> one-to-many or one-to-one <=> one-to-one.

edit : Althought it seems possible (if not semantically correct) to make a one-to-one <=> one-to-many mapping, my question is about many-to-one <=> one-to-one.

I know that there are already some answers about one-to-one vs many-to-one on this site, but I didn't found an answer to my question in these posts.

Thank you for your time.

Steve Marion
  • 289
  • 1
  • 9
  • This post doesn't answer my question as I do care about both side of the mapping. – Steve Marion Sep 08 '15 at 13:36
  • 1
    It's just a question about, which one table has a foreign key column. In this case it's a Person, and it's many-to-one relation can be represented as one-to-one. – Stanislav Sep 08 '15 at 13:43
  • Ok but that's not my question. I ask, considering that multiple persons can have the same address, is using one-to-one in Address wrong ? why should it work/not work ? – Steve Marion Sep 08 '15 at 13:48

1 Answers1

1

If you have the unique constraint in the DB, then it would not be possible that two persons have the same address.

However, if the constraint is missing and there really are multiple persons with the same address, then this mapping is not correct and you may get an exception or wrong/unpredictable results when accessing the person association in the Address entity.

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
  • OK so in this example the many-to-one is in fact a one-to-one in disguise, and a many-to-one <=> one-to-one mapping is incorrect without the unique constraint. – Steve Marion Sep 08 '15 at 14:58
  • True. But it _can_ be correct if you never associate the same address with two persons; Hibernate will not perform any checks against it on its own, it's the database job to do it. With the constraint, you just make better consistency guaranties and make your intention clear that this is a one-to-one association. – Dragan Bozanovic Sep 08 '15 at 15:36