Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active April 7, 2021 04:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rponte/5212789 to your computer and use it in GitHub Desktop.
Save rponte/5212789 to your computer and use it in GitHub Desktop.
Handling Hibernate (JPA) lazy association mapping when using @NotFound
@Entity
public class Parent {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@NotFound(action=NotFoundAction.IGNORE) // You don't need this annotation if you use the approach below
private Son son;
public Son getSon() {
if(!Hibernate.isInitialized(son)) {
try {
Hibernate.initialize(son);
} catch(org.hibernate.ObjectNotFoundException one) {
son = null;
}
}
return son;
}
}
@rponte
Copy link
Author

rponte commented Mar 21, 2013

Why is this necessary? Because when you use @NotFound Hibernate ignores the lazy attitude of the field and makes it as if it was annotated EAGER.

More informations,
http://chekkal.blogspot.com.br/2012/09/hibernate-lazy-loading-and-notfound.html

@Pawan-Mishra
Copy link

How i define @NotFound in Hibernate XML mapping?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment