Proxy Objects,Eager and Lazy Fetch Types

Lazy Initialisation:

Lazy Fetch Types:

Lazy Initialisation do not initialise the entire object,it first initialise only the first level variables and it initialise the second level such as a list of address only when we actually want to access it.

Lazy intialization is the default behaviour of Hibernate

Now in our example suppose we have to fetch the values for UserDetails with primary-Id as 1,we will fetch it as below,

user1 = (UserDetails)session.get(UserDetails.class, 1);

At this point if we do an inspect on user1 in eclipse you will see below:

lazyloading

Observer the attributes of listOfAddress,

The bag = null & initalized = false

So  user1 will have the values of the first level member variables

Now when we call user1.getListOfAddresses() when required then at this point the list gets populated and if we do and inspect at this point you will observe that the bag is now populated with the values and initalized=true.

lazyloading2

 

Output:

Now suppose we have a requirement that we need to access the values of the list even after we close the session then  how to do that.

Eager Fetch Types:

That can be achieved using Eager loading with the annotation @ElementCollection(fetch=FetchType.EAGER)

So if we want to retrive the values even when we use the get() method we can do it with FetchType.EAGER.

ElementCollection(fetch=FetchType.EAGER)
@JoinTable(name=”USER_ADDRESS”,
joinColumns=@JoinColumn(name=”USER_ID”)
)
/*@GenericGenerator(name=”sequence-gen”,strategy=”sequence”)
@CollectionId(columns = { @Column(name=”ADDRESS_ID”) }, generator = “sequence-gen”, type = @Type(type=”long”))
private Collection<Address> listOfAddresses = new ArrayList<Address>();

public Collection<Address> getListOfAddresses() {
return listOfAddresses;
}


 

   

Share :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Comments are closed