gpt4 book ai didi

java - QueryDSL JPA- 与 group by 无关的自连接

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:30 24 4
gpt4 key购买 nike

有什么方法可以使用 QueryDSL 获取此查询吗?

select
person.name,
count(neighbors.*)
from person as neighbors
where person.address = neighbor.address
group by person.name

address 不是 FK。

最佳答案

第一个问题的关键是使用别名来进行自连接:

// 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;
}
}

关于java - QueryDSL JPA- 与 group by 无关的自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32892745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com