0

Hibernate Supports lazy loading by default for one to many/many to one and many to many associations . but Hibernate does NOT support lazy loading for one-to-one relationships. Lets have following examples for Parent and Children scenarios.

one Person has one Address Parent Entity Is Defined as.

@Entity
@Table(name = “Person”)
public class Person {

...

private Address address;

@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@Join Column(name="PERSON_ID", insert able=false, null able=false)
public Address get Address() {
return address;

...

}

And child entity Is defined as

@Entity
@Table(name = “Address”)
public class Address {

...

private Person person;

@OneToOne(mapped By="person")
public Person get Person() {
return person;

...

}

In above scenarios it should be lazy loading but actually hibernate is producing eager loading. Two select statement fires at same time 1) select for parent entity in this case Person 2) select for child entity in this case address

so how could i use lazy loading for one to one mapping in hibernate?

Waqas Ahmed
  • 4,801
  • 3
  • 36
  • 45

1 Answers1

0

Having several ways to implement a one-to-one association in Hibernate, you can map it as many-to-one instead (for both sides). That would allow you to enable lazy loading and is the way to go when the foreign key is stored as a field in the table to be associated.

The reason is simple: You don’t care what’s on the target side of the association, so you can treat it like a to-one association without the many part. All you want is to express “This entity has a property that is a reference to an instance of another entity” and use a foreign key field to represent that relationship.

See also:

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217