简体   繁体   中英

Hibernate LazyInitializationException: could not initialize proxy - no Session

I have structure like this mapped in Hibernate (using XDoclet because it is old project):

public class Student {
     String name;
     int age;
     School school;    //many to one
     // ...
}

public class School {
     String name;
     // ...
}

I would like to print student's school name (using student object), like this:

System.out.println("School name: " + student.getSchool().getName());

but I am getting:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

I wouldn't like to change mappings files (because I am not author of this), so what is other solution of this problem?

How did you read Student object?
Because if you are reading a Student from a method that close the session before returning, accessing a @Lazy collection will generate a LazyInitializationException .
I suggest you to check your session lifecycle.

make sure your code calls the accessor methods of student before the session is closed. or in the case you are using spring and transactions, then it has to be under the scope where your session is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM