4

I'm looking at filtering in my query to return entities where locations intersects with the queries locations. From the method signature it seems that the eqAny method is the way to go.

The only downside is that it doesn't accept a collection, but only a CollectionExpression. How do I create a CollectionExpression from my collection?

My (non compiling) code is along these lines:

import com.mysema.query.types.expr.BooleanExpression;
//…
StringPath locations = … //irrelevant
BooleanExpression predicate = anotherPredicate.and(qbuilder.locations.eqAny(query.getLocations().orElse(new HashSet<>())));
iwein
  • 25,788
  • 10
  • 70
  • 111

1 Answers1

0

I am pretty sure you found a solution after so long, however, as I faced the same issue (and could not find any help on how to do it), I post my own solution in case someone is in the same place.

First, let's suppose my class is the following,

public class MyClass {

    private String id;
    private String name;

    // All the Getters, Setters, Constructors, etc
}

As a result, the equivalent auto-generated QueryDSL class will be QMyClass

What I did is to manually create my BooleanExpression by iterating through my Collection, something like the following (let's suppose the collections are List<String> ids and List<String> names),

QMyClass myClass = QMyClass.myClass;

BooleanExpression be = null;

if (!CollectionUtils.isEmpty(ids)) {
   be = myClass.id.equalsIgnoreCase(ids.get(0));
   if (ids.size() > 1) {
       for (int i = 1; i < ids.size(); i++) {
           be = be.or(myClass.id.equalsIgnoreCase(ids.get(i)));
       }
   }
}

if (!CollectionUtils.isEmpty(names)) {
   be = be.and(myClass.name.equalsIgnoreCase(names.get(0)));
   if (names.size() > 1) {
      for (int i = 1; i < names.size(); i++) {
          be = be.or(myClass.name.equalsIgnoreCase(names.get(i)));
      }
   }
}

After that, the rest was easy. I simply had to extend MyClassRepository interface as following (in order to take advantage of QueryDSL functionalities),

public interface MyClassRepository extends extends JpaRepository<MyClass, Serializable>, QuerydslPredicateExecutor {

...

}

Finally, I used the findAll Repository method (extended now of course by default due to QueryDSL) as following (I used a Pageable as well for my case but that's optional of course),

Page<MyClass> myClassList = this.myClassRepository(be, pageable);
dZ.
  • 404
  • 1
  • 5
  • 9