JPA Criteria API - where condition with field on subclass

蹲街弑〆低调 提交于 2020-07-09 05:32:10

问题


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

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