3

I using Query DSL generated entity EntitySerializer in order to query JPA entities using QueryDSL (integrated with SpringData).

I’m receiving from the client property names and I want to create predicates for the properties that can be added (AND) to additional predicats.

I don’t know how to get from the EntitySerializer the predicate/Path that matches my property name. For example, let’s say we have a Person entity (with auto generated QPerson class) with a “name” property that I want to filter on (at the end I want to create a generic method). Here is the generic method:

Public Predicat getPredicatByPropertyName(String propertyName)  {
      QPerson p = QPerson.person;
      person.getPredicat(“propertyName”).like(“tom”);
}
Noam Nevo
  • 3,021
  • 10
  • 35
  • 49

3 Answers3

6

To create a String typed property just use the following snippet

new StringPath(p, propertyName)

which can then be used like this to create a Predicate instance

new StringPath(p, propertyName).like("tom")
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111
6

I did it slightly different since as Timo said didn't work straightforward, here is it:

query.from(play);
query.where( Expressions.stringPath(play, "name").eq("New play") );

I know it could also be achieved by doing it separately:

StringPath column = Expressions.stringPath(play, "name");

query.from(play);
query.where( column.eq("New play") );
M.Octavio
  • 1,780
  • 2
  • 25
  • 39
0

As of QueryDSL 5.0, I found two ways to do this independent of the column class:

First way: using just reflection:

Field pathField = p.getClass().getField(reportField.getFieldName());
ComparableExpressionBase<?> path = (ComparableExpressionBase<?>)
pathField.get(p);

Note: I use the ComparableExpressionBase class because it is extendend by all "path classes" that I found and it also can be used in select, orderBy and other functions to build the query

Second way: using reflection and ExpressionUtils:

Class<?> pParameterClass = (Class<?>) ((ParameterizedType) p.getClass().getGenericSuperclass())
            .getActualTypeArguments()[0];
Class<?> pathClass = pParameterClass.getDeclaredField(pathName).getDeclaringClass();
Path<?> path = ExpressionUtils.path(pathClass, p, pathName);

Note: using this way we first get the class of the entity of the table see this answer for an explanation on how to get a parametrized type. Next, we get the class of the path and finally we get the path with the ExpressionUtils.path method.