带有Subselect和Group By的JPA谓词

时间:2014-01-10 15:14:33

标签: jpa group-by tuples predicate subquery

我需要在子查询中使用CriteriaQuery<Tuple>来获取我需要的数据。我似乎无法弄清楚的是如何在我的Predicate中指定它。

对于此示例,我们希望返回指定州内每个县的最新人口数据。

这是给我完全符合我想要的结果的SQL:

select * from TB_POPULATION
where (COUNTY_ID, EFFECTIVE_DATE) in
      ( select COUNTY_ID, max(EFFECTIVE_DATE) from TB_POPULATION
        where STATE_ID = 47
        group by COUNTY_ID
      )
and STATE_ID = 47
;

此时我有一个PopulationDataBean实体:

@Entity
@Table(name = "TB_POPULATION")
public class PopulationDataBean {
    @Temporal(TemporalType.DATE)
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    @Column(name = "EFFECTIVE_DATE", nullable = false)
    private LocalDate effectiveDate;
    @Column(name = "STATE_ID", precision = 15, scale = 0, nullable = false)
    private Long stateId;
    @Column(name = "COUNTY_ID", precision = 15, scale = 0, nullable = false)
    private Long countyId;
    @Column(name = "POPULATION", precision = 9, scale = 0, nullable = false)
    private Long popCount;
    ...
}

我可以创建返回Tuple的子查询,但我无法弄清楚如何指定子查询结果需要匹配main where子句中的PopulationDataBean_.countyIdPopulationDataBean_.effectiveDate。< / p>

0 个答案:

没有答案