Hibernate: Mapping a “one-to-zero-or-one” relationship

I’ve been searching a way to do a lazy a “one-to-zero-or-one”
relationship in Hibernate and I finally found a way to do it using
many-to-one with unique=”true”. See example below:

Association: Person [1 <--> 0..1] Note

<class name=”Person” table=”person”>
<id name=”id” column=”id” type=”int” unsaved-value=”-1″>
<generator class=”sequence”>
<param name=”sequence”father_id_seq</param>
</generator>
</id>
<property name=”name” type=”string”/>
<many-to-one name=”note” class=”Note” column=”id”
unique=”true” insert=”false” update=”false”
cascade=”all”/>
</class>

<class name=”Note” table=”note”>
<id name=”id” column=”id” type=”int” unsaved-value=”-1″ >
<generator class=”foreign”>
<param name=”property”>owner</param>
</generator>
</id>
<property name=”note” type=”string”/>
<one-to-one name=”owner” class=”Person” constrained=”true”/>
</class>

Observe that column “id” is used twice in Person mapping.I’ve been
searching a way to do a lazy a “one-to-zero-or-one” relationship in
Hibernate and I finally found a way to do it using many-to-one with
unique=”true”. See example below:

Association: Person [1 <--> 0..1] Note

<class name=”Person” table=”person”>
<id name=”id” column=”id” type=”int” unsaved-value=”-1″>
<generator class=”sequence”>
<param name=”sequence”father_id_seq</param>
</generator>
</id>
<property name=”name” type=”string”/>
<many-to-one name=”note” class=”Note” column=”id”
unique=”true” insert=”false” update=”false”
cascade=”all”/>
</class>

<class name=”Note” table=”note”>
<id name=”id” column=”id” type=”int” unsaved-value=”-1″ >
<generator class=”foreign”>
<param name=”property”>owner</param>
</generator>
</id>
<property name=”note” type=”string”/>
<one-to-one name=”owner” class=”Person” constrained=”true”/>
</class>

Observe that column “id” is used twice in Person mapping.

1 comment

  1. I blog often and I really thank you for your content. Your article has truly peaked
    my interest. I’m going to take a note of your blog and keep checking for new information about once a week.
    I opted in for your RSS feed as well.

    Here is my page – medical blog

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *