【问题标题】:How can I write an EXISTS predicate on a collection attribute in Criteria API?如何在 Criteria API 中的集合属性上编写 EXISTS 谓词?
【发布时间】:2017-02-22 21:11:15
【问题描述】:

我有这些课程:

@Entity
public class Customer {

    @Id long id;

    String name;

    @OneToMany List<Customer> related;

}

我正在使用这个 JPQL 查询:

select c from Customer c where c.name = 'ACME'
    or exists( select 1 from c.related r where r.name = 'ACME' )

如何使用 Criteria API 编写相同的查询?我需要将exists 与子查询一起使用,例如 JPQL,但我不知道如何从 Criteria API 中的集合属性创建子查询。

【问题讨论】:

    标签: jpa jpql criteria-api


    【解决方案1】:

    这样的事情会给EXISTS (subquery)

    Subquery<Long> sq = cq.subquery(Long.class);
    Root<Customer> customerSub = sq.correlate(customer);
    Join<Customer,Customer> related = customerSub.join(Customer_.related);
    ... extra config of subquery
    
    Predicate existsCustomer = cb.exists(sq);
    

    其中cqCriteriaQuerycbCriteriaBuilder。这来自 JPA 2.1 规范 p323 示例 4 中的一个示例

    【讨论】:

    • 如何将子查询限制为related 集合属性?
    • 在外部进行 JOIN,然后使用该外部别名在子查询中应用 where 子句?
    • 我不能使用 JOINs,我正在寻找相同的 SQL 查询结果,而 JPQL 版本不产生任何 JOIN。我需要像subquery.from( root.get( "related" ) ) 这样的东西,但from 想要实体而不是路径……
    猜你喜欢
    • 2016-06-23
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2020-10-17
    • 2011-09-04
    相关资源
    最近更新 更多