conversion sql query to jpa

后端 未结 1 438
野性不改
野性不改 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<Object[]> criteria = builder.createQuery(Object[].class); 
    Root<Department> root = criteria.from(Department.class);
    Path<String> name = root.get("name");
    
    Join<Department, Employee> employee = root.join("employees", JoinType.LEFT);
    
    Expression<Long> 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<Object[]> query = em.createQuery(criteria);
    
    0 讨论(0)
提交回复
热议问题