使用 QueryDSL 进行多重连接

Multiple Joins with QueryDSL

我正在尝试将 QueryDSL 与 Spring Data JPA 一起使用。

我的数据库有 3 个 table。

1) 一个帐户 table,其中包含帐户信息,特别是帐号。 2) 一个 PersonRole table,它具有一个人在帐户上的角色(如所有者)以及相应的帐号和他的个人 ID 号。 3) 一个人 table 有几排人。他们的身份证号码和名字、姓氏等...

我的实体如下所示:

@Entity
Account{
//...Other fields ommited
// **
@OneToMany
@JoinColumn(name = "ACCNT_NUMBER")
List<PersonRole> personRoles;**
}

@Entity
PersonRole{
String role;
// ...Other fields ommited
// **
@OneToOne
@JoinColumn(name = "PERSON_ID")
Person person;**
}


@Entity
Person{...}

我想按人的名字和姓氏过滤我 select 的帐户,然后使用它来填充具有相关人员角色和人员的合同实体。

我假设我必须创建联接才能执行此操作。我尝试了很多东西,但我不断收到错误。我已经创建了相应的 QClasses。我知道下面的代码是错误的并且它不起作用但也许你可以看看我是否在正确的轨道上并且可能帮助我。任何帮助是极大的赞赏。谢谢!

    QAccount account = QAccount.account;
    QPersonRole personRoles = QPersonRole.personRole;
    QPerson person = QPerson.person;

    JPAQuery<Account> query = new JPAQuery<>(entityManager);

    List<Account> accountList = query
            .from(account)
            .innerJoin(acccount.personRoles, personRoles)
            .innerJoin(person)
            .where(person.lastName.eq("John")
                    .and(person.lastName.eq("Doe")))
            .fetch();

只有当你想过滤一对多时你才需要加入...仍然可以利用 jpql...而且我更愿意在 personRole 上使用单数所以:

QAccount account = QAccount.account;
QPersonRole personRole = QPersonRole.personRole;

JPAQuery<Account> query = new JPAQuery<>(entityManager);

List<Account> accountList = query
            .from(account)
            .innerJoin(acccount.personRoles, personRole)
            .where(personRole.person.lastName.eq("John")
                    .and(personRole.person.lastName.eq("Doe")))
            .fetch();

请注意如何不需要加入 Person。