JOOQ - 如何使用字段列表

时间:2018-03-20 16:25:26

标签: java jooq

我有一个包含三个表的DDBB:loan,person和loan_person_rel以及每个表的相应POJO。

贷款

private int line;
private Double balance;
private Double expired;
private int state;
private int defaultDays;
private Branch branch;
private String balanceHistory;
private String expiredHistory;
private Long loanCode;
private List<Person> persons;
private String extraInfo;
private LoanTypes loanType;
private String nomPro;
//The class contains the getters and setters :)

private String name;
private String documentNumber;
private String workEnterprise;
private String workCity;
private String workAddress;
private String workNeighborhood;
private String workPhone;
private String occupation;
private String homePhone;
private String cellPhone;
private String phone3;
private String phone4;
private String homeAddress;
private String homeCity;
private String homeNeighborhood;
private String email;
private String relationship;
private List<Loan> loans;
//The class contains the getters and setters :)

Loan_person_rel

private String personId;
private String loanId;
private int type;
//The class contains the getters and setters :)

我如何构建一个JOOQ选择或一些方法来检索数据并填充已填充字段persons的类贷款?

2 个答案:

答案 0 :(得分:1)

一定是这样:

List<Loan*> list = dsl.selectFrom(Loan).fetch(this::recordToPojo);

private Loan recordToPojo(final LoanRecord record) {
    return new Loan(
            record.getLine(),
            record.getBalance(),
            ....
    );
}

*贷款 - pojo的名字!

答案 1 :(得分:0)

从 jOOQ 3.14 开始,这里的首选方法是 nest your collections directly in SQL using SQL/XML or SQL/JSON。你可以写一个这样的查询:

List<Loan> result =
ctx.select(
      // Project the loan columns you need, or all of them using LOAN.asterisk()
      LOAN.LINE,
      LOAN.BALANCE,
      ...
      field(select(
        jsonArrayAgg(jsonObject(
          key("name").value(PERSON.NAME),
          key("documentNumber").value(PERSON.DOCUMENT_NUMBER),
          ...
        ))
        .from(PERSON)
        .join(LOAN_PERSON_REL)
        .on(PERSON.PERSON_ID.eq(LOAN.PERSON_REL.PERSON_ID))
        .where(LOAN_PERSON_REL.LOAN_ID.eq(LOAN.LOAN_ID))
      )).as("persons")
    )
   .from(LOAN)
   .fetchInto(Loan.class);

与基于 JPA 的 ORM 不同,jOOQ 不提供对象持久性,即您的 Person 对象不能包含返回 Loan 对象的基于身份的引用。相反,这种方法以树形式投影数据,这可能适合您的用例。

请注意,JSON_ARRAYAGG() 将空集聚合为 NULL,而不是空集 []If that's a problem, use COALESCE()