Java Predicates In 子句:非法参数异常?

Java Predicates In clause: illegal argument exception?

我正在尝试创建一个 java predicate 来获取与特定 ID 匹配的所有实体:

 public Predicate createPredicate(List<Integer> personIds){
 
 Predicate newPredicate = null;
 if(!personIds.isEmpty()){
      CriteriaBuilder.In<Integer> inClause = builder.in(from.get(PERSON_ID));
      for (Integer personId : personIds) {
        inClause.value(personId);
      }
      newPredicate = builder.in(inClause);
    }

    return newPredicate;
  }

然而,当我尝试从中获取计数结果时(见下文),我得到一个 illegal argument exception

问题是什么?

private Long getResultsCount(Predicate predicate) throws ATSException {

    CriteriaBuilder countBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> countQuery = countBuilder.createQuery(Long.class);
    Root<Person> countFrom = countQuery.from(Person.class);
    countQuery = countQuery.select(countBuilder.count(countFrom));
   
    countQuery.where(predicate);

    return entityManager.createQuery(countQuery).getSingleResult();
  }

错误:

   java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: in near line 1, column 177 [select count(generatedAlias0) from com.model.Person as generatedAlias0 where ( generatedAlias0.status=:param0 ) and ( ( generatedAlias0.personId in () in () ) and ( ( generatedAlias0.personId in () in () ) and ( generatedAlias0.personId in () in () ) ) )]\r\n\tat org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)\r\n\tat 

生成的查询包含以下3次:

( generatedAlias0.personId in () in () )

我猜是这个原因:

newPredicate = builder.in(inClause);

inClause 已经翻译成“in (...)”,因此您要求标准生成器在 IN.[=19 中包含 IN =]

如果删除该行,您的代码是否有效?

而且使用 Expression.in 方法可能更容易。由于 from.get(PERSON_ID) returns 和 Expression,这应该有效:

public Predicate createPredicate(List<Integer> personIds){
    return personIds.isEmpty()
            ? null
            : from.get(PERSON_ID).in(personIds);
}