use criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Restrictions don't work for createAlias
-
04-07-2023 - |
Domanda
Here is my problem:
I want to do something like this query via hibernate criteria
select employee.name, employee.surname, department.name, position.name, department_position.end_date
from employee, department_position, department, position
where employee.id = department_position.employee_id
and department_position.department_id = department.id
and department_position.position_id = position.id
and department_position.end_date is null
I have class Employee
mapped to employee table
public class Employee {
private int id;
private String name;
private String surname;
private Date startDate;
private Date endDate;
private Set<DepartmentPosition> positions;
}
and DepartmentPosition
(with all setters and getters of course)
public class DepartmentPosition {
private int id;
private Department department;
private Position position;
private Employee employee;
private Date startDate;
private Date endDate;
}
And I'm using this criteria
session.createCriteria(Employee.class)
.createAlias("Positions", "pos")
.add(Restrictions.isNull("pos.EndDate"));
Only 1 employee in my db matches this query (and he has 1 position with null
endDate
), but in resulting list it is repeated 3 times (looks like because this employee has 3 positions total)
How can i fix this?
Thanks for your replies
Soluzione
Altri suggerimenti
Try to use restriction like Restrictions.isNull("Employee.Position.EndDate")
- you did not specified in Restriction
that Position
is a property of Employee
.
You should create the criteria on positions object then use projection to get the employee.
Criteria criteria = session.createCriteria(DepartmentPosition.class)
.add(Restrictions.isNull("endDate"));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.distinct(Projections.property("employee")));
criteria.setProjection(projList);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow