Question

I am consulting the docs from http://www.querydsl.com/static/querydsl/3.2.1/reference/pdf/Querydsl_Reference.pdf

There I see the example

QDepartment department = QDepartment.department;
QDepartment d = new QDepartment("d");
query.from(department)
 .where(department.employees.size().eq(
      new JPASubQuery().from(d).unique(d.employees.size().max())
 )).list(department);

I tried to execute the query using my tables with the code below:

QAdminEntity tableAdmin = QAdminEntity.adminEntity;
JPAQuery query = queryFrom( tableAdmin ).where(
    tableAdmin.id_city.eq( idCity ).and(
        tableAdmin.problems.size().eq(
            subQueryFrom( tableAdmin ).unique(
                tableAdmin.problems.size().min()
            )
        )
    )
);

return query.singleResult( tableAdmin );

That code gives me an error, something like "Aggregate function calls cannot be nested".

I am sorry for my lack of expertise on postgres and querydsl, but I suppose this should be very straightforward.

The resulted query:

select
    adminentit0_.id_admin as id1_3_,
    adminentit0_.ds_email as ds2_3_,
    adminentit0_.ds_name as ds3_3_,
    adminentit0_.ds_password as ds4_3_,
    adminentit0_.ds_username as ds5_3_,
    adminentit0_.id_city as id6_3_,
    adminentit0_.id_permission as id7_3_ 
from
    m_admin adminentit0_ 
where
    adminentit0_.id_city=? 
    and (
        select
            count(problems1_.id_admin) 
        from
            m_problem problems1_ 
        where
            adminentit0_.id_admin=problems1_.id_admin
    )=(
        select
            min(count(problems3_.id_admin)) 
        from
            m_admin adminentit2_,
            m_problem problems3_ 
        where
            adminentit2_.id_admin=problems3_.id_admin
        ) limit ?

As you can see I want to list the admin that have less problems than everyone else from the relation admin -> problems.

How can I make this work?

Adittional question:
Is it necessary to get another "QAdminEntity" field for the subQuery or that "d" variable from the "new QDepartment("d")" code is just for the example?

Was it helpful?

Solution

The following query should have similar semantics

QAdminEntity adminEntity = QAdminEntity.adminEntity;
JPAQuery query = query.from(adminEntity)
    .where(adminEntity.id_city.eq(idCity))
    .orderBy(adminEntity.problems.size().asc())
    .limit(1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top