Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional one-to-one mapping in Hibernate

How do I create an optional one-to-one mapping in the hibernate hbm file? For example, suppose that I have a User and a last_visited_page table. The user may or may not have a last_visited page. Here is my current one-to-one mapping in the hbm file:

User Class:

<one-to-one name="lastVisitedPage" class="LastVisitedPage" cascade="save-update">

LastVisitedPage Class:

<one-to-one name="user" class="user" constrained="true" />

The above example does not allow the creation of a user who does not have a last visited page. A freshly created user has not visited any pages yet. How do I change the hbm mapping to make the userPrefs mapping optional?

like image 329
hibernate Avatar asked May 06 '10 20:05

hibernate


People also ask

How do you make a one to one relationship in hibernate?

Define Hibernate Mapping FileThe <many-to-one> element will be used to define the rule to establish a one-to-one relationship between EMPLOYEE and ADDRESS entities, but column attribute will be set to unique constraint and rest of the mapping file will remain as it was in case of many-to-one association.

What is JPA one to one mapping?

In JPA One-To-One mapping, a single instance of one entity is associated with another single instance of another entity. Basically, a single-valued association is implemented by JPA One-To-One Mapping.

What is optional in hibernate?

Java 8 introduced Optional<T> as a container object which may contain null values. It's often used to indicate to a caller that a value might be null and that it need to be handled to avoid NullPointerExceptions.


2 Answers

Just spend most of the day today trying to do a similar thing, finally found the following solution (just in-case this might be useful for other people)

@OneToOne
@JoinColumn(name="ClassA_Id", referencedColumnName="ClassB_Id", nullable=true)

Hope that might help save somebody some time

like image 45
JustDanyul Avatar answered Sep 28 '22 01:09

JustDanyul


To my knowledge, Hibernate doesn't support optional one-to-one (see HHH-2007) so you'll have to use a fake many-to-one with not-null="false" instead.

like image 120
Pascal Thivent Avatar answered Sep 28 '22 00:09

Pascal Thivent