Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL - order by count as alias

I'm using queryDSL to get users with some additional data from base:

public List<Tuple> getUsersWithData (final SomeParam someParam) {
  QUser user = QUser.user;
  QRecord record = QRecord.record;
  JPQLQuery = query = new JPAQuery(getEntityManager());

  NumberPath<Long> cAlias = Expressions.numberPath(Long.class, "cAlias");
  return query.from(user)
       .leftJoin(record).on(record.someParam.eq(someParam))
       .where(user.active.eq(true))
       .groupBy(user)
       .orderBy(cAlias.asc())
       .list(user, record.countDistinct().as(cAlias));
}

Despite it's working as desired, it generates two COUNT() in SQL:

SELECT
  t0.ID
  t0.NAME
  to.ACTIVE
  COUNT(DISTINCT (t1.ID))
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY COUNT(DISTINCT (t1.ID))

I want to know if it's possible to get something like this:

SELECT
  t0.ID
  t0.NAME
  to.ACTIVE
  COUNT(DISTINCT (t1.ID)) as cAlias
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY cAlias

I failed to understand this from documentation, please, give me some directions if it's possible.

like image 922
Svininykh Kirill Avatar asked Jul 22 '16 08:07

Svininykh Kirill


1 Answers

    QVehicle qVehicle = QVehicle.vehicle;

    NumberPath<Long> aliasQuantity = Expressions.numberPath(Long.class, "quantity");
    final List<QuantityByTypeVO> quantityByTypeVO = new JPAQueryFactory(getEntityManager())
            .select(Projections.constructor(QuantityByTypeVO.class, qVehicle.tipo, qVehicle.count().as(aliasQuantity)))
            .from(qVehicle)
            .groupBy(qVehicle.type)
            .orderBy(aliasQuantity.desc())
            .fetch();

    select 
       vehicleges0_.type as col_0_0_, count(vehicleges0_.pk) as col_1_0_ 
    from vehicle vehicleges0_ 
    group by vehicleges0_.type 
    order by col_1_0_ desc;

I did something like that, but I did count first before ordering. Look the query and the select generated.

like image 182
Terrão Avatar answered Nov 01 '22 14:11

Terrão