Multiple Joins with QueryDSL

心已入冬 提交于 2019-12-08 09:21:41

问题


I'm trying to use QueryDSL with Spring Data JPA.

My database has 3 tables.

1) An account table with account info and specifically an account number. 2) A PersonRole table which has a person's role on an account (like owner) and the corresponding account number and his person ID number. 3) A person table which has rows of persons. Their ID number and first name, last name etc...

My entities look like this:

@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{...}

I want to filter the accounts that I select by person first name and last name and then use that to populate contract entities which have associated personroles and persons.

I assume I have to create joins to do this. I tried a bunch of things but I keep getting errors. I've created the corresponding QClasses. I know the below code is wrong and it doesn't work but perhaps you can see if I'm on the right track and possibly help me. Any help is greatly appreciated. Thank you!

    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();

回答1:


You only need joins when you want to filter on one to many... jpql can still be leveraged... and I'd prefer to use a singular on the personRole so:

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();

Notice how the join to Person is not necessary.



来源:https://stackoverflow.com/questions/45822230/multiple-joins-with-querydsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!