我有一个疑问
SELECT d.name, count(e.id) FROM department d LEFT OUTER JOIN employee e on e.department_id = d.id and e.salary > 5000
以及如何将其转换为 jpa 现在我有:
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);
我通过删除排序和分组来简化这两个示例 谁能告诉我如何修改我的 jpa 代码以获得与 sql 查询相同的结果
提前致谢
最佳答案
你离结果不远了。问题是,据我所知,您无法使用 JPA 对 on
子句添加任何限制。因此查询必须重写为
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)
这是与此查询等效的未测试的查询):
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);
关于jpa-2.0 - 将sql查询转换为jpa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7848582/