hibernate
hibernate

Reputation: 747

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?

Upvotes: 19

Views: 42450

Answers (5)

Tolomeo Nogo
Tolomeo Nogo

Reputation: 91

Had the same issue, resolved with @OneToOne(optional = true) on the User class (hibernate 5.2.17.Final)

Upvotes: 8

JustDanyul
JustDanyul

Reputation: 14044

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

Upvotes: 15

davidemm
davidemm

Reputation: 2009

I was having a simliar problem, but using annotations. Google brought me here, so if anyone else finds themselves in the same sitatuions, this worked for me:

http://opensource.atlassian.com/projects/hibernate/browse/ANN-725

If you're using annotations, you can use the @NotFound(action=NotFoundAction.IGNORE) annotation so that you don't get an exception. Just make sure your code checks for nulls because it's now might not be there ;-)

Upvotes: 7

Erwin Smout
Erwin Smout

Reputation: 18408

If a user has at most one last_visited page, then there are two cases :

(a) some given user has no last_visited page, in which case there will not be any tuple for this user in the last_visited_page table, (b) some given user has exactly one last_visited page, in which case there will be exactly one tuple for this user in the last_visited_page table.

That should make it obvious that userid is a candidate key in your last-visited-page table.

And that should make it obvious that you should declare that key to the DBMS.

Upvotes: 0

Pascal Thivent
Pascal Thivent

Reputation: 570375

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.

Upvotes: 15

Related Questions