I have a problem with Hibernate and the LazyInitializationException. I searched and find a lot of answers, but I can not use them to solve my problem, because I have to say, I am new to Hibernate.
I run JUnit tests, in case of the error this one:
@Test
public void testAddPerson() {
Set<Person> persons = service.getAllPersons();
// create new person
Person person = new Person();
person.setEmail("john@doe.com");
Project testProject = serviceProj.findProjectById(1);
HashSet<Project> lister = new HashSet<Project>();
lister.add(testProject);
person.setProjects(lister);
service.addPerson(person);
testProject.getPersons().add(person);
...
}
The last shown line:
testProject.getPersons().add(person);
throws this error:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.doe.john.domain.Project.persons, no session or session was closed
Person and Project are bidirectional n:m:
Person.java:
@ManyToMany(mappedBy="persons")
private Set<Project> projects = new HashSet<Project>();
Project.java:
@ManyToMany
@JoinTable(name = "Project_Person",
joinColumns = {@JoinColumn(name="project_id", referencedColumnName="id")},
inverseJoinColumns = {@JoinColumn(name="person_id", referencedColumnName="id")}
)
private Set<Person> persons = new HashSet<Person>();
So what’s the problem?
The problem is that by default the collection is lazily loaded. This means that it wont actually be loaded from the database until it is being accessed. In order to load it you will need a active session/transaction.
The easy way out is to change it to FethType.EAGER which makes sure that the collection is populated straight away.
–update–
I’ve recently had the very same problem and I ended up modifying my actual service to deal with this sort of thing. Declare a addPerson method in your ProjectService class.