@Entity
public class User {
@ManyToMany(cascade = { MERGE, PERSIST, CascadeType.REFRESH }, fetch = LAZY)
@Cache(usage = READ_WRITE)
@UserRoles
private List<Role> roles = new ArrayList<Role>(0);
}
Collections get loaded even when they are declared as Lazy, what could be the reason that it is getting loaded even when it is declared as Lazy
According to the JPA 2.0 specification lazy fetching is a hint to the persistence provider.
Section 11.1.6 says:
There are cases in which the provider might determine that it makes no sense to lazily fetch something, or perhaps a provider may not even implement lazy fetching.
The PersistenceUtil.isLoaded methods can be used to determine the load state of an entity
and its attributes regardless of the persistence unit with which the entity is associated.
To be sure you are facing this kind of problem you should use this method. Of course, if a entity got detached, a simple inspection of the lazily fetched field could help as well.
Other than this, I cannot see a particular reason, based on the code posted of why your collections is not being lazily fetched. I think that perhaps the fact that you are using 2nd level cache could be affecting in this case, but this is something I have not verified, it is just a hunch.
[EDIT-1]
There is also an issue with lazy loading if you are using final classes. The Hibernate documentation says under persistent classes:
[EDIT-2]
Besides this the JPA 2.0 Specification in section 2.1 specifies that entities must not be final:
This same requirement is later specified for embeddables in section 2.5.
I do not have access to the JPA 1.0 specification, but I am quite confident that this requirement applies to it as well. Try it and see if this is the reason and let us know.