我想使用标准
获取此SQLselect A.evaluated_employee_id, A.created_date, A.total_grade
from employee_performance_assessment A
join
( select evaluated_employee_id, max(created_date) as maxdate, status, total_grade
from employee_performance_assessment
group by evaluated_employee_id
) B on A.evaluated_employee_id = B.evaluated_employee_id and A.created_date = B.maxDate
我正在做以下
DetachedCriteria dc = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class);
dc.createAlias("evaluatedEmployee", "e");
dc.setProjection(Projections.projectionList().add(Projections.max("createdDate"))
.add(Projections.groupProperty("evaluatedEmployee")));
dc.addOrder(Order.asc("e.lastName")).addOrder(Order.asc("createdDate"));
dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return getDAOHibernateTemplate().findByCriteria(dc);
但是这会在WHERE子句中生成子查询 知道如何从同一个表(类)中加入两个标准吗?
答案 0 :(得分:4)
找到解决方案。基本上改变了原始查询:
select A.evaluated_employee_id, A.created_date, A.total_grade
from employee_performance_assessment A
where A.created_date =
( select max(created_date)
from employee_performance_assessment
where A.evaluated_employee_id = evaluated_employee_id
group by evaluated_employee_id
)
因此,我不是加入子查询,而是在where子句中比较created_date。 休眠中的等价物是:
DetachedCriteria dc = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class, "performanceAssessment");
dc.createAlias("evaluatedEmployee", "e");
dc.addOrder(Order.asc("e.lastName")).addOrder(Order.asc("createdDate"));
if (assessmentsSearch.isOnlyLastAssessment()){
DetachedCriteria dc2 = DetachedCriteria.forClass(EmployeePerformanceAssessmentBO.class, "performanceAssessmentSubQuery");
dc2.setProjection(Projections.projectionList().add(Projections.max("createdDate")));
dc2.add(Expression.eqProperty("performanceAssessment.evaluatedEmployee.id", "performanceAssessmentSubQuery.evaluatedEmployee.id"));
dc.add(Subqueries.propertyEq("createdDate", dc2));
}
希望它可以帮助别人。