如何使用subselect和max编写查询的hibernate标准

时间:2016-01-19 16:20:50

标签: sql hibernate criteria

我有一个包含此字段的实体:

  • id(pk)
  • Id_remuneration_str
  • Id_salary_item

该实体存储每个期间以及每个薪酬结构和工资项目的价格,我需要一个查询来检索每个薪酬结构和工资项目的最后价格。

有效的sql查询是:

select * from ep_remuneration_str_price p1 
where ((100*year) + month) =  
( 
 select max(((100*year) + month)) 
 from ep_remuneration_str_price p2 
 where p1.id_remuneration_str = p2.id_remuneration_str and 
 p1.id_salary_item = p2.id_salary_item 
 group by ID_SALARY_ITEM
);

如何翻译成条件查询?

提前致谢

大家好,只是查询我在我的实体中添加了一个日期,以避免年和月之间的操作

select * from ep_remuneration_str_price
where date in 
(  select max(date) 
from ep_remuneration_str_price pinner
where ep_remuneration_str_price.id_remuneration_str = pinner.id_remuneration_str and
   ep_remuneration_str_price.id_salary_item = pinner.id_salary_item
group by id_remuneration_str,ID_SALARY_ITEM
);

我尝试了这种代码的和平:

        DetachedCriteria maxDateQuery = DetachedCriteria.forClass(LocalDate.class, "p_inner");
    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.max("date"));
    proj.add(Projections.groupProperty("id_remuneration_str"));
    proj.add(Projections.groupProperty("idSalaryItem"));
    maxDateQuery.setProjection(proj);
    maxDateQuery.add(Expression.eqProperty("ep_remuneration_str_price.id_remuneration_str", "p_inner.id_remuneration_str"));
    maxDateQuery.add(Expression.eqProperty("ep_remuneration_str_price.id_salary_item", "p_inner.id_salary_item"));

    CriteriaBuilder criteriaBuilder = this.getCriteriaBuilder();
    CriteriaQuery<RemunerationStructurePriceEntity> criteriaQuery = this.getCriteriaQuery();
    Root<RemunerationStructurePriceEntity> from = this.getCriteriaFrom(criteriaQuery);

    Predicate predicate = criteriaBuilder.in(from.get("date")).value(maxDateQuery);

    List<RemunerationStructurePriceEntity> result = (List<RemunerationStructurePriceEntity>) findByCriteriaQuery(criteriaQuery, from, criteriaBuilder, predicate);

我收到了这个错误:

Caused by: java.lang.IllegalArgumentException: Parameter value [DetachableCriteria(CriteriaImpl(org.joda.time.LocalDate:p_inner[][ep_remuneration_str_price.id_remuneration_str=p_inner.id_remuneration_str, ep_remuneration_str_price.id_salary_item=p_inner.id_salary_item][max(date), id_remuneration_str, idSalaryItem]))] did not match expected type [org.joda.time.LocalDate (n/a)] at java.lang.IllegalArgumentException: Parameter value [DetachableCriteria(CriteriaImpl(org.joda.time.LocalDate:p_inner[][ep_remuneration_str_price.id_remuneration_str=p_inner.id_remuneration_str, ep_remuneration_str_price.id_salary_item=p_inner.id_salary_item][max(date), id_remuneration_str, idSalaryItem]))] did not match expected type [org.joda.time.LocalDate (n/a)]

有什么问题?

0 个答案:

没有答案