Two Laptop Bag
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes @Basic(fetch = FetchType.LAZY) does not work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "@Basic(fetch = FetchType.LAZY) does not work" Watch "@Basic(fetch = FetchType.LAZY) does not work" New topic

@Basic(fetch = FetchType.LAZY) does not work

Rohit Aggarawal
Ranch Hand

Joined: Jun 26, 2009
Posts: 39
Created simple entity using simple stateless session bean. After creating new entity bean, perform look up stateless session bean again and perform find. I am surprised that on the server console, the attribute that is to be loaded lazily is also fetched. Please help me on this.

SCJP 6.0

Girish Vasmatkar
Ranch Hand

Joined: Apr 24, 2008
Posts: 201
Hi Rohit,

No, It won't throw an exception. From what I know of lazy loading, the property is not fetched untill it is explicitly referenced. So, in your case it might not have been fetched but since you are referencing it explicitly it is then fetched from the persistence context or the database. To test wether it is working you can enable logging and see what query is fired and what result you are getting.
Experts please correct me if I am wrong.

Rohit Aggarawal
Ranch Hand

Joined: Jun 26, 2009
Posts: 39
I have verified the same at my end again. I called up the method simply find using entity Manager and that generate the following SQL query at the console

Thanks for the response. Please look into this again and let me know your thoguhts on it.
ryan sukale
Ranch Hand

Joined: Aug 11, 2007
Posts: 53
Hi Rohit,

@Basic(fetch = FetchType.LAZY) is only a hint to the persistence provider to fetch a property lazily. It is not a compulsion becasue fetching the annotated field is not going to cause any damage.

The perisistence provider can choose to completely ignore the LAZY fetching annotation and fetch the value like an ordinary field.

An exception will be thrown only in the case when the persistence provider actually fullfills the LAZY fetching request and you try to access the lazily fetched property when the entity gets detached and its lazily fetched properties were not accessed when it was managed. Since in your case, the peristence provider did not honour the LAZY fetching request, you did not get any exception.

So, i suppose your issue is related to the persistence provider that you are using.

Hope this helps :>

Ryan Sukale

SCJP 5.0, SCWCD 5.0, SCBCD 5.0
I agree. Here's the link:
subject: @Basic(fetch = FetchType.LAZY) does not work
It's not a secret anymore!