LazyFetch Issue with OneToMany relationships
Hello
I have three entities:
User, UserBatch, UserAttribute
In my User entity I have:
@OneToMany(cascade = CascadeType.ALL, mappedBy ="userid")
private Set<Userbatch> userbatchCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy ="userid")
private Set<Userattribute> userattributeCollection;
In UserBatch and UserAttribute entities i have:
@JoinColumn(name ="USERID", referencedColumnName ="USERID")
@ManyToOne
private Userprofile userid;
In Session bean, I have the following method to find a User:
public User findUser(Long userId){
return em.find(User.class, userId);
}
Now in my client, if i do the following:
User up = mysession.findUser(Long.valueOf(9));
System.out.println(up.getUserattributeCollection().size());
I get the following exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entities.User.userattributeCollection, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97)
at org.hibernate.collection.PersistentSet.size(PersistentSet.java:114)
If I make the following changes everything works fine:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy ="userid")
private Set<Userattribute> userattributeCollection;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy ="userid")
private Set<Userbatch> userbatchCollection;
But i do not want to use EAGER since the User table has a lot of data and everytime there is a query for User, all the related collections will be Eagerly fetched.
What should I do?
Thanks

