有没有办法用QueryDSL获取此查询?
select
person.name,
count(neighbors.*)
from person as neighbors
where person.address = neighbor.address
group by person.name
其中address
不是FK。
答案 0 :(得分:3)
第一个问题的关键是使用别名来进行自联接:
// static instance uses default alias "person"
QPerson person = QPerson.person;
QPerson neighbor = new QPerson("neighbor");
JPAQuery query = new JPAQuery(em)
.from(person, neighbor)
.where(person.adress.eq(neighbor.adress))
.groupBy(person.name);
要获得结果,您只需使用Tuple类:
List<Tuple> results = query.list(person.name, neighbor.count());
for (Tuple row : result) {
System.out.println("name: " + row.get(person.name));
System.out.println("count: " + row.get(neighbor.count()));
}
或者您可以使用ConstructorExpression
执行以下操作:
List<MyResult> results = query.list(ConstructorExpression.create(
MyResult.class, person.name, neighbor.count()));
public class MyResult {
private String name;
private long count;
public MyResult(String name, long count) {
this.name = name;
this.count = count;
}
}