将sql查询转换为jpa

时间:2011-10-21 11:10:36

标签: jpa-2.0

我有一个查询

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查询相同的结果

提前致谢

1 个答案:

答案 0 :(得分:2)

你离结果不远了。问题是,AFAIK,你不能使用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);