使用QueryDsl从子查询创建别名

时间:2018-06-22 08:56:24

标签: java hibernate jpa java-ee querydsl

我的目标是改造SQL query

select a.*, (select count(DOGS.DOG_ID) from DOGS where a.DOG_ID = 
DOGS.DOG_ID) cnt
from ANIMALS a
order by cnt desc ;

我这样创建一个QueryDsl查询:

createQuery()
            .select(Projections.constructor(AnimalsDto.class, animal.animalId, animal.firstName,
                    Expressions.as(subQueryForDogsCount(dogs, animal), "cnt")))
            .from(animal).orderBy(new OrderSpecifier<>(Order.ASC, Expressions.asString("cnt"))).fetch();

subQueryForDogsCount就是:

JPAExpressions.select(dogs.count()).from(dogs)
            .where(dogs.dogId.eq(animal.dogId));

当我记录该查询时,我得到的是这样的东西:

[select 
animal.animalId, 
prospect.firstName,  
(select count(DOGS.dogId)
from DOGS dogs
where dogs.dogId = animal.dogId) as cnt
from ANIMAL animal
order by ?1 desc]

当我想执行它时,我得到一个NullPointerExpception,我认为问题可能出在此时的最后一个清单上:?1。为什么querydsl看不到该别名?也许还有其他方法可以为其创建别名?

0 个答案:

没有答案