简体   繁体   中英

QueryDSL dynamic predicate chaining

How to use QueryDSL to dynamically build and chain predicates.

I have a UI with a datatable. Each column has a box where you can enter one filter term. Like so:

用户界面

In the example above eventno filter = "0288" and address filter = "drive". These are then sent by the UI to the backend in a pagination object, which contains a map of column names and filter strings. Like so:

分页

In my backend with QueryDSL I now need to dynamically construct a Predicate based on the terms provided for the columns. I have tried this for just the address event and address column, but it does not seem to filter both.

public Page<EpisodeDashboard> getPage(int pageNumber, int pageSize, Sort sort, PaginationCriteria pagination) {
    BooleanBuilder where = new BooleanBuilder();
    if (pagination.getFilterBy().getMapOfFilters().get("eventno")!=null) {
        where.and(qEpisode.eventno.containsIgnoreCase(pagination.getFilterBy().getMapOfFilters().get("eventno")));
        }
    if (pagination.getFilterBy().getMapOfFilters().get("address")!=null) {
        where.and(qEpisode.address.formattedAddress.containsIgnoreCase(pagination.getFilterBy().getMapOfFilters().get("address")));
        }
    List<Episode> e = episodeRepository.findAll(where);

I probably want something with a for each key/value in the hashmap to dynamically construct the predicates.

The above code actually works, but :

episodeRepository.findAll(where);

Returns a iterable and most of my project uses List. So I modified the Episode Repo with a override to:

    @Override
    List<Episode> findAll(Predicate predicate);

Now a list is returned and the code works. An enhancement on this answer would be if the "if" statements could be generated by iterating over the pagination filter hashmap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM