Hello all!
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("[email protected]");
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?