conversion sql query to jpa

后端 未结 1 437
野性不改
野性不改 2021-01-14 20:55

I have a query

SELECT d.name, count(e.id) FROM department d LEFT OUTER JOIN employee e on e.department_id = d.id and e.salary > 5000

and

1条回答
  •  攒了一身酷
    2021-01-14 21:38

    You're not far from the result. The problem is that, AFAIK, you can't add any restriction on the on clause, using JPA. So the query wil have to be rewritten as

    SELECT d.name, count(e.id) FROM department d 
    LEFT OUTER JOIN employee e on e.department_id = d.id 
    where (e.id is null or e.salary > 5000)
    

    Here is the equivalent of this query not tested):

    CriteriaQuery criteria = builder.createQuery(Object[].class); 
    Root root = criteria.from(Department.class);
    Path name = root.get("name");
    
    Join employee = root.join("employees", JoinType.LEFT);
    
    Expression empCount = builder.count(employee.get("id"));
    criteria.multiselect(name,empCount);
    criteria.where(builder.or(builder.isNull(employee.get("id")),
                              builder.gt(employee.get("salary"), 5000)));
    
    TypedQuery query = em.createQuery(criteria);
    

    0 讨论(0)
提交回复
热议问题