Hi everyone,
I have a problem with ManyToOne relations with optional parameter set to true. I have a Project entity that contains a ManyToOne optional relationship to a ProjectEVA entity. Also I have another entity called ProjectBaseline that has a many to one relationship with Project.
Now, I have the following query:
SELECT t FROM ProjectBaseline AS t INNER JOIN FETCH t.project k2 LEFT JOIN FETCH t.project.projectEVA k5 [... other left join fetch here] WHERE t.project.companyId = ?1 AND t.isLast = ?2 ORDER BY t.name ASC
in my dao.
The problem is that when i do baseline.getProject().getProjectEVA() for a project that does not have a projectEVA I get the proxy for the project eva object and when I want to use this object in the jsp page a lazy initialization exception appears. I tried in my code to check for the projects that do not have a projecteva by testing if baseline.getProject().getProjectEVA() != null, but since the above call returns the projecteva proxy this is always true. So the enxt thing I tried was to try to initialize the proxy using Hibernate.initialize(baseline.getProject().getProjectEVA()), but now I get an EntityNotFoundException saying that it cannot find the entity.
I read
http://www.hibernate.org/315.html and I was expecting that since I was using the LEFT JOIN FETCH for the projecteva entity in the query, the projectEVA field would be set to null, if no entity was found for the query.
Thanks for your help.
The code looks like this:
Code:
//this code generates the above query
PaginatedListWrapper<T> wrappedBaselines = projectDAO
.findAllBaselines(wrapper, company, engineeringArea, projectState, costCenter, includeCloseProjects,
search,
workerLogin, pmoArea, loads);
List<ProjectBaseline> baselines = (List<ProjectBaseline>) wrappedBaselines.getList();
for (ProjectBaseline baseline : baselines) {
ProjectEVA projectEVA = null;
Hibernate.initialize(baseline.getProject().getProjectEVA());
//initially i expected here null for projects without eva, but got the proxy
if(baseline.getProject().getProjectEVA() != null){
projectEVA = baseline.getProject().getProjectEVA();
} else {
/*
* If there is no projectEVA defined for the baseline(this is possible because the the relation between projects and projectEVA is optional)
* then use a projectEVA that has only 0 or null values.
*/
log.info(MessageFormat.format("There is no projectEVA defined for baseline {0}. Creating an empty WISEProjectEVA for the baseline's project eva decorator.", baseline.getId()));
projectEVA = new ProjectEVA();
}
baseline.setProjectEVADecorator(new WISEProjectEVA(projectEVA, null));
}