本文介绍了JPA Criteria API-子类中带字段的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为问题的实体和一个名为 UserIssue 的实体。 UserIssue 扩展了 Issue

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;

    ...
}

我需要做

Predicate predicate= root.get("category").in(IssueCategory.CATEGORY_1, IssueCategory.CATEGORY_2);

问题在于,根是 Root< Issue> 的实例但类别字段是在子类 UserIssue 上定义的,因此该行代码显然无法正常工作。

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.

是否有一种方法可以构建谓词创建子类字段的条件?我只有 Root< Issue>,CriteriaQuery和CriteriaBuilder 的实例。

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.

谢谢,
Lukas

Thank you,Lukas

推荐答案

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

这篇关于JPA Criteria API-子类中带字段的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 20:48