Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting dynamic property predicate by property name with queryDSL

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”);
}
like image 560
Noam Nevo Avatar asked Dec 17 '25 23:12

Noam Nevo


2 Answers

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")
like image 89
Timo Westkämper Avatar answered Dec 19 '25 11:12

Timo Westkämper


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") );
like image 37
M.Octavio Avatar answered Dec 19 '25 12:12

M.Octavio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!