William William - 8 days ago 4
Java Question

Hibernate mapping xml one-to-one (many-to-one)

I'm trying to map a relationship between two classes which have a one-to-one relationship. After looking up on the internet it seems like people prefer to map it using many-to-one.

For example have have a class Order and a class Bill. Bill holds a FK to the invoice.

Here is my mapping for Bill:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 21, 2016 10:46:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="domain.Bill" table="BILL">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>

<many-to-one name="order" class="domain.Order" column="ORDER_ID" unique="true" not-null="true"/>
</class>
</hibernate-mapping>


As you can see above, in my mapping of Bill I can specify the column of Fk to the Order, but what should I put in my mapping for Order since it does not have a Fk to Bill?

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 21, 2016 10:46:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="domain.Order" table="ORDER">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>

<many-to-one name="bill" class="domain.Bill" ???? fetch="select"/>

</class>
</hibernate-mapping>

Answer

You should try to map it as it is: one-to-one.

The only reason that I am aware of why people may recommend many-to-one is because of the lazy loading issues on the inverse side of the one-to-one associations. Then you probably want a fake one-to-many association on the inverse side (after all it's the only logical inverse side of many-to-one).

However, take a look at this answer for different alternatives.