QueryDSL - account order as an alias

I use queryDSL to get users with some additional data from the database:

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));
}

Although it works as desired, it generates two COUNT () values ​​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 is 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 did not understand this from the documentation, please give me some directions if possible.

+4
source share
2 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 similar, but first of all I ordered an account. See the query and the generated selection.

+1
source

, SQL, queryDSL. - , , , . , COUNT() .

0

Source: https://habr.com/ru/post/1648752/


All Articles