Querydsl SQL 一对多关系投影到具有嵌套列表的对象无法正常工作

问题描述 投票:0回答:1

我在数据库中有简单的关系

账户

id 名字
1 欧元账户
2 美元账户

账户设置

id 账户 ID 名字 价值
1 1 初级 真实
2 1 活跃 真实
3 1 颞叶
4 2 活跃

我想将两个表中的连接数据投影到以下 DTO 类中:

public class Account {
  private Long id;
  private String name;
  private List<AccountSetting> accountSettings;

  public Account(Long id, String name, List<AccountSetting> accountSettings) {
    this.id = id;
    this.name = name;
    this.accountSettings = accountSettings;
  }

  // getters setters
} 
public class AccountSetting {
  private String name;
  private boolean value;

  public AccountSetting(String name, boolean value) {
    this.name = name;
    this.value = value;
  }

  // getters setters
}

我已经为此数据库生成了 Q 类。

我尝试使用分组设置投影:

PostgreSQLQuery<Tuple> result = sqlQueryFactory
      .select(
        account.id,
        account.name,
        accountSetting.name,
        accountSetting.value)
      .from(account)
      .join(accountSetting).on(accountSetting.accountId.eq(account.id));

Map<Long, Account> resultMap = result.transform(
      GroupBy.groupBy(
        account.id
      ).as(
        Projections.constructor(
          Account.class,
          account.id,
          account.name,
          list(Projections.constructor(
              AccountSetting.class,
              accountSetting.name,
              accountSetting.value
            )
          )
        )
      )
    );

还在选择中绑定投影,如下所示:

    PostgreSQLQuery<Account> accountRows = sqlQueryFactory
      .select(Projections.constructor(
          Account.class,
          account.id,
          account.name,
          list(Projections.constructor(
              AccountSetting.class,
              accountSetting.name,
              accountSetting.value
            )
          )
        )
      )
      .from(account)
      .join(accountSetting).on(accountSetting.accountId.eq(account.id));

每次我都得到 accountSettings 的嵌套单元素列表(而不是 account.id=1 的 3 个设置和 account.id=2 的 1 个设置列表)

我正在使用querydsl v5.0.0。

我将不胜感激任何建议...

我找到了许多与 QueryDSL 结果投影相关的答案(主要与 QueryDSL JPA 或 QueryDSL Collections 相关)。可能对于 QueryDSL SQL 我做错了什么?

我已经检查过: https://github.com/querydsl/querydsl/blob/cd608f04ed7534b1b62a78a28beb141071d149b6/querydsl-collections/src/test/java/com/querydsl/collections/GroupByTest.java#L219C17-L219C42

https://github.com/querydsl/querydsl/blob/cd608f04ed7534b1b62a78a28beb141071d149b6/querydsl-core/src/test/java/com/querydsl/core/group/GroupByListTest.java#L185

作为参考,但它对我来说并没有达到预期的效果。

java postgresql querydsl
1个回答
0
投票

可能太晚了,但请检查一下您是否使用了正确的“列表”方法

你应该使用来自

的列表
import static com.querydsl.core.group.GroupBy.list;

import static com.querydsl.core.types.Projections.list;
© www.soinside.com 2019 - 2024. All rights reserved.