conversion sql query to jpa

佐手、 提交于 2019-12-30 11:13:12

问题


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 how i can convert this to jpa right now i have:

CriteriaQuery<Object[]> criteria = builder.createQuery(Object[].class); 
Root<Department> root = criteria.from(Department.class);
Path<String> name = root.get("name");
Expression<Long> empCount = builder.count(root.get("employees").get("id"));
criteria.multiselect(name,empCount);
TypedQuery<Object[]> query = em.createQuery(criteria);

I simplified both examples by removing ordering and grouping can anyone tell me how i can modifie my jpa code to get same reslults like from my sql query

thanks in advance


回答1:


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


来源:https://stackoverflow.com/questions/7848582/conversion-sql-query-to-jpa

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