Home Ask Login Register

Developers Planet

Your answer is one click away!

jayb0b February 2016

QueryDSL: building a query from an entity

I've just started integrating QueryDSL into a Spring Boot project and I'm looking for a way to build a query out of an existing entity bean. Using @ModelAttribute it's nice and easy to pass in an entity via a GET request from the controller as long as the parameters align with the bean:

public Page<Company> getLogins(@ModelAttribute Company company, Pageable pageable, @RequestParam(value = "page", required = false) String pageNumber){
    return companyService.findbyParameters(company,pageNumber);


And in the service class, I can use the BooleanBuilder to build up a query:

    public Page<Company> findbyParameters(Company companySearch,String pageNumber){
        QCompany company = QCompany.company;
        BooleanBuilder builder = new BooleanBuilder();
        if (companySearch.getEmail() != null && !companySearch.getEmail().equals("")){
        if (companySearch.getCompanyName() != null && !companySearch.getCompanyName().equals("")){
       //add other clauses...
       return loginRepository.findAll(builder.getValue(),pageableService.getPageRequest(pageNumber));

..and this works fine. But it seems like an unnecessary amount of plumbing since I'll have to write similar, longwinded conditional code for each entity I'm working with. I reckon that reflection might be an option, but I'm not sure if QueryDSL has something built in that handles this situation. I've looked at the QueryDSL docs and nothing jumped out at me.

So is there a nice, tidy way of handling this situation without clogging up my service classes with boilerplate?


Ali Dehghani February 2016

You can use Spring Data's QueryDSL integration. Basically, you extend the QueryDslPredicateExecutor in your repository interface and it add a findAll method that gets a QueryDSL Predicate and filter all the results based on that Predicate. You see more details here.

Post Status

Asked in February 2016
Viewed 3,594 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life