问题
I have entity called Issue
and entity called UserIssue
. UserIssue
extends Issue
.
@Inheritance(strategy = InheritanceType.JOINED)
@Entity(name = "ISSUE")
public class Issue extends VersionedSequenceIdEntity {
... all fields
}
@Entity(name = "USER_ISSUE")
public class UserIssue extends Issue {
...
@Enumerated(EnumType.STRING)
@Column(name = "CATEGORY", nullable = false)
private IssueCategory category;
...
}
I need to do e.g. something like this:
Predicate predicate= root.get("category").in(IssueCategory.CATEGORY_1, IssueCategory.CATEGORY_2);
The problem is that root is instance of Root<Issue>
but "category" field is defined on subclass UserIssue
so the line of code obviously does not work.
Is there a way how to build a predicate that creates where condition for subclass field? I have only instance of Root<Issue>, CriteriaQuery and CriteriaBuilder
.
Thank you, Lukas
回答1:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Issue> issueQuery = cb.createQuery(Issue.class);
Root<Issue> issueRoot = issueQuery.from(Issue.class);
Subquery<UserIssue> subQuery = issueQuery.subquery(UserIssue.class);
Root<UserIssue> userIssueRoot = subQuery.from(UserIssue.class);
Predicate predicate= userIssueRoot.get("category")
.in(IssueCategory.CATEGORY_1, IssueCategory.CATEGORY_2);
subQuery.select(userIssueRoot).where(predicate);
issueQuery.select(issueRoot).where(issueRoot.get("id").in(subQuery));
em.createQuery(issueQuery).getResultList();
来源:https://stackoverflow.com/questions/62695214/jpa-criteria-api-where-condition-with-field-on-subclass