James Relic
James Relic

Reputation: 85

JPA 2.0 predicate condition lists in query builder

Code:

List<Predicate> conditionsList = new ArrayList<Predicate>();
Predicate onStart = criteriaBuilder.greaterThanOrEqualTo(criteriaRoot.get("insertDateTime"), startTradeDate);
Predicate onEnd = criteriaBuilder.lessThanOrEqualTo(criteriaRoot.get("insertDateTime"), endTradeDate);
conditionsList.add(onStart);
conditionsList.add(onEnd);

CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<MyClass> criteriaQuery = 
criteriaBuilder.createQuery(MyClass.class);
Root<MyClass> criteriaRoot = criteriaQuery.from(MyClass.class);
criteriaQuery.select(criteriaRoot).where(conditionsList);

The last line above doesn't compile because its expecting the conditionsList object to be a List of Boolean not list of Predicate.

Please advise me on the correct way of adding predicates above to the hibernate criteria?

Upvotes: 1

Views: 1545

Answers (1)

perissf
perissf

Reputation: 16273

Convert the List<Predicate> into an array Predicate[] like this:

criteriaQuery.select(criteriaRoot).where(conditionsList.toArray(new Predicate[] {}));

Upvotes: 1

Related Questions