简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM