JPA Criteria API - where 条件与子类上的字段
JPA Criteria API - where condition with field on subclass
我有实体 Issue
和实体 UserIssue
。 UserIssue
扩展 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;
...
}
我需要做,例如像这样:
Predicate predicate= root.get("category").in(IssueCategory.CATEGORY_1, IssueCategory.CATEGORY_2);
问题是 root 是 Root<Issue>
的实例,但是“category”字段是在子类 UserIssue
上定义的,所以这行代码显然不起作用。
有没有办法构建一个谓词来为子类字段创建 where 条件?我只有 Root<Issue>, CriteriaQuery and CriteriaBuilder
.
的实例
谢谢,
卢卡斯
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();
我有实体 Issue
和实体 UserIssue
。 UserIssue
扩展 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;
...
}
我需要做,例如像这样:
Predicate predicate= root.get("category").in(IssueCategory.CATEGORY_1, IssueCategory.CATEGORY_2);
问题是 root 是 Root<Issue>
的实例,但是“category”字段是在子类 UserIssue
上定义的,所以这行代码显然不起作用。
有没有办法构建一个谓词来为子类字段创建 where 条件?我只有 Root<Issue>, CriteriaQuery and CriteriaBuilder
.
谢谢, 卢卡斯
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();