• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting lazy initialization exception.

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using spring ORM and getting lazy initialization exception while retrieving the associated object. The scenario is as follows:

There is a user table which is associated with group table. In the User.hbm.xml the lazy attribute is marked as false.

Now I want to get the user and want to access the group objects user is associated with in different class.

The way I am retrieving the User is as follows, Suppose I want to get this in my class Example

class Example{
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("Spring xml files");

foo(){
UserDao userDao= (User) appContext.getBean("userDao");
user usr = UserDao.getUser();
usr.getGroups(); //giving lazy initialization exception
}
}

UserDao is a dao class that intracts with the database using hibernate APIs


This lazy initialization exception is obvious as I am loading the object in one session and trying to access the associated object in different session.


Is there any way to get away with it apart from making the lazy attribute false? (Keeping in mind that I cannot touch the existing files)
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe this method: "user usr = UserDao.getUser();" is closing your database connection.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
database conncetions are fine....More over the problem is related with the two different session as I am retreiving the User in one session and trying to load the associated object in different session.
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
john sal wrote:database conncetions are fine....More over the problem is related with the two different session as I am retreiving the User in one session and trying to load the associated object in different session.


After you load it in the first session do a usr.getGroups().size(). And you will be fine. Or use a namedQuery with fetch.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic