JPA Criteria API - 带连接的子查询

时间:2018-05-29 22:05:16

标签: hibernate jpa jpa-criteria

如何在JPA Criteria API中编写此JPQL查询?

SELECT t FROM TvShow t
WHERE (
    SELECT COUNT(g)
    FROM Genre g
    WHERE t MEMBER OF g.tvShows
) <= 2

1 个答案:

答案 0 :(得分:0)

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TvShow> criteriaQuery = criteriaBuilder.createQuery(TvShow.class);
    Root<Service> from = criteriaQuery.from(TvShow.class);
    CriteriaQuery<TvShow> select = criteriaQuery.select(from);

    Subquery<Long> subQueryGenre = select.subquery(Long.class);
    Root<Genre> fromGenre = subQueryGenre.from(Genre.class);
    subQueryGenre.select(criteriaBuilder.count(fromGenre));
    subQueryGenre.where(criteriaBuilder.equal(from, fromGenre.get("tvShows")));

    select.where(criteriaBuilder.lessThanOrEqualTo(subQueryGenre , 2));
    TypedQuery<TvShow> typedQuery = entityManager.createQuery(select);
    try {
        return typedQuery.getResultList();
    } catch (Exception ex) {
        return = new ArrayList<TvShow>();
    }