conversion sql query to jpa

别等时光非礼了梦想. 提交于 2019-12-01 12:11:39

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!