我正在尝试使用 JPA (eclipselink) 中的标准 api 创建以下句子,它简单地询问某个类别中是否存在某些用户
我想要的句子:
SELECT
CASE
WHEN EXISTS
(SELECT * FROM user WHERE category = ?)
THEN true
ELSE false
END
bind => [10]
我尝试使用此代码:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Boolean> criteriaQuery = criteriaBuilder.createQuery(Boolean.class);
Root<T> root = criteriaQuery.from(tclass);
Subquery<T> subquery = criteriaQuery.subquery(tclass);
Root<T> subroot = subquery.from(tclass);
subquery.select(subroot);
Predicate subPredicate = criteriaBuilder.equal(subroot.get("category"),category);
subquery.where(subPredicate);
Predicate predicateExists = criteriaBuilder.exists(subquery);
Case<Boolean> booleancase = criteriaBuilder.<Boolean>selectCase();
Expression<Boolean> booleanExpression =
booleancase.when(predicateExists,true)
.otherwise(false);
criteriaQuery.select(booleanExpression);
TypedQuery<Boolean> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.getResultList();
可悲的是,我的句子如下,我想删除最后一个“来自用户”:
SELECT
CASE
WHEN EXISTS
(SELECT ? FROM user t1 WHERE (t1.category = ?))
THEN ?
ELSE ?
END
FROM user t0
bind => [1, 110, true, false]
任何想法?