Really dynamic JPA CriteriaBuilder

好久不见. 提交于 2019-11-27 06:10:37

You can pass an array of predicates to the CriteriaBuilder, deciding on equal or like as you go. For this, build a list and pack the contents of the list into an array in a single and statement. Like this:

final List<Predicate> predicates = new ArrayList<Predicate>();

for (final Entry<String, String> e : myPredicateMap.entrySet()) {

    final String key = e.getKey();
    final String value = e.getValue();

    if ((key != null) && (value != null)) {

        if (value.contains("%")) {
            predicates.add(criteriaBuilder.like(root.<String> get(key), value));
        } else {
            predicates.add(criteriaBuilder.equal(root.get(key), value));
        }
    }
}

query.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
query.select(count);

In case you need to distingiush between and and or, use two lists.

One option is to use the fact that method with variable number of arguments can take an array:

query.where(predicates.toArray(new Predicate[predicates.size()])); 

Alternatively, you can combine them into a single predicate (note that if you don't do it, you don't need to create a conjunction as in your example);:

Predicate where = cb.conjunction();
while (column.hasNext()) {
    ...
    where = cb.and(where, cb.equal(userRoot.get(colIndex), colValue));
}

query.where(where);

I have always been thinking that creation of solution like that is like reinventing the bicycle. Here https://github.com/sasa7812/jfbdemo is my solution. It was tested on EclipseLink and Hibernate (EclipseLink in production, we used it in several projects for simple cases). Sometimes you just need a quick solution to make a dataTable with sorting and filtering, nothing fancy. It is able to filter and sort on joined fields, and even on collections. Project contains demo on Primefaces showing the abilities of FilterCriteriaBuilder. In the heart of it you just need this:

 public List<T> loadFilterBuilder(int first, int pageSize, Map<String, Boolean> sorts, List<FieldFilter> argumentFilters, Class<? extends AbstractEntity> entityClass) {
    FilterCriteriaBuilder<T> fcb = new FilterCriteriaBuilder<>(getEntityManager(), (Class<T>) entityClass);
    fcb.addFilters(argumentFilters).addOrders(sorts);
    Query q = getEntityManager().createQuery(fcb.getQuery());
    q.setFirstResult(first);
    q.setMaxResults(pageSize);
    return q.getResultList();
}

to get the results from database.

I really need someone to tell me that it is usefull and is used somewhere to continue my work on this library.

For Predicate you can create new ArrayList add all your predicate to the list and then at the end you can create a predicate array and convert list to predicate array and directly assign it to criteriabuilder.where(new Pridicate[])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!