Hibernate LazyInitializationException

People who use Hibernate will surely come across this irritating exception. In my whole career I have encountered this several times. Actually this problem is quite easily to fix. Let's start with when this exception can occur... Most of the time it has to do with a collection that is mapped to some objects that are lazily loaded. Lazy loading is used when you don't need the collection every time you retrieve the specific object. So i.e. you have an object called Person that can have multiple PhoneNumber objects. The objects will look something like this:

public class Person {
private String name;
private Integer age;
private Set phoneNumbers;
.....
}

public class PhoneNumber {
private String areaCode;


private String number;
private Person person;
.....
}

Having mapped the collection as lazy (Hibernate3 defaults to lazy) the call to the collection will cause an LazyInitializationException when you try to call it after you retrieved in i.e. the GUI layer or in another service where you pass this object. This problem can easily be fixed by just calling the person.getPhoneNumbers() after you retrieved it with your DAO. This will cause Hibernate to retrieve the elements in the collection from the database. In the GUI now you can just use the collection to display the phone numbers i.e. So the key thing here is to initialize the collection that is lazy initialized.

Comments

Popular posts from this blog

Fastest XML parser

Tomcat behind Apache HTTP server using Spring Security

Cargo-itest open source project