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