Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate one to zero or one mapping

Tags:

java

hibernate

I'm trying to map a one to "zero or one" relationship in Hibernate. I think I may have found a way using a many-to-one.

class A {
  private B b;
  // ... getters and setters
}

class B {
  private A a;
}

Class A's mapping specifies:

<many-to-one name="b" class="B" 
insert="false" update="false" 
column="id" unique="true"/>

and Class B's mapping specifies:

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

What I would like is for b to be null when no matching row for B was found in the database. So I can do this (in class A):

if (b == null)

However, it seems that b is never null.

What can I do about this?

like image 937
Boden Avatar asked May 08 '09 19:05

Boden


2 Answers

Like Boden said, the answer is to add not-found="ignore" to the many-to-one statement in A. Doing this with annotation:

In Class A:

@ManyToOne
@Cascade({ CascadeType.ALL })
@JoinColumn(name = "Id")
@NotFound(action=NotFoundAction.IGNORE)
private B b

in Class B:

@Id
@GeneratedValue(generator = "myForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
    name = "myForeignGenerator",
    strategy = "foreign",
    parameters = @Parameter(name = "property", value = "a")
)
private Long subscriberId;

@OneToOne(mappedBy="b")
@PrimaryKeyJoinColumn
@NotFound(action=NotFoundAction.IGNORE)
private A a;
like image 87
Tony Avatar answered Sep 27 '22 21:09

Tony


The answer was to add not-found="ignore" to the many-to-one statement in A:

<many-to-one name="b" class="B" not-found="ignore" insert="false" update="false" column="id" unique="true"/>

I tried simply adding lazy="false" to B as Rob H recommended, but that resulted in a HibernateObjectRetrievalFailureException everytime I loaded an A that had no B.

See this thread for more information:

https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e

like image 41
Boden Avatar answered Sep 27 '22 22:09

Boden