计算多个表中的实体

时间:2013-03-23 13:40:10

标签: java jpa-2.0 jpql

我有一个非实体类

public class CountryStatistics {

    public CountryStatistics(Long numTowns, Long numVillages) {
    ...
    }

}

对于给定的国家/地区,我想构建一个统计对象。

国家,村庄和城市是实体,所以我尝试了下面的代码。

String queryString = 
"SELECT NEW mypackage.CountryStatistics(count(t), count(v)) 
 FROM Town t, Village v WHERE t.country = :country AND v.country = :country"

TypedQuery<CountryStatistics> query = 
em.createQuery(queryString ,CountryStatistics.class).setParameter("country", country);

query.getSingleResult()

问题:在同一查询中计算不同表中某些实体的正确方法是什么?

通过上面的查询,如果我像下面那样区分,我最终将获得高数字,城镇数量将是正确的。

"SELECT NEW mypackage.CountryStatistics(count(distinct t), count(v)) 
 FROM Town t, Village v WHERE t.country = :country AND v.country = :country"

但如果我把它设置为村庄,我也会得到:

java.sql.SQLSyntaxErrorException: Multiple DISTINCT aggregates are not supported at this time.

1 个答案:

答案 0 :(得分:2)

以下查询(未经测试)应该执行您想要的操作:

select count(distinct t.id), count(distinct v.id) from Country c
left join c.towns t
left join c.villages v
where c.id = :countryId