users@glassfish.java.net

Re: Lazy/eager fetch question

From: <glassfish_at_javadesktop.org>
Date: Thu, 08 Feb 2007 04:09:28 PST

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
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
[Message sent by forum member 'rabbiaqaswar' (rabbiaqaswar)]

http://forums.java.net/jive/thread.jspa?messageID=202638