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

[2538 byte] By [rabbiaa] at [2007-11-26 17:47:08]
# 1

1. You misunderstand how Hibernate work. The first, you code correctly but If you want to access getUserattributeCollection in Client layer. It is evident that there is an exception is raised. The reason is the layer that Hibernate container manage session is different from Client layer. Ex: Client layer is desktop side (ex Swing) and Hibernate layer is in server side (Tomcat). For this the code getUserattributeCollection is executed in Client side will throw a Lazy Exception. But I am sure that if you access getUserattributeCollection on Server side. It will not throw an exception.

2. if you set fetch = FetchType.EAGER. It mean when you retrieve a User. Hibernate will retrieve getUserattributeCollection. For this, there is no exception here and it run well.

Message was edited by:

lochdsmile

lochdsmilea at 2007-7-9 4:59:26 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...