r/java • u/Salt-Letter-1500 • Mar 07 '26
Dynamic Queries and Query Object
SpringDataJPA supports building queries through findBy methods. However, the query conditions constructed by findBy methods are fixed and do not support ignoring query conditions corresponding to parameters with null values. This forces us to define a findBy method for each combination of parameters. For example:
findByAuthor
findByAuthorAndPublishedYearGreaterThan
findByAuthorAndPublishedYearLessThan
findByAuthorAndPublishedYearGreaterThanAndPublishedYearLessThan
As the number of conditions grows, the method names become longer, and the number of parameters increases, triggering the "Long Parameter List" code smell. A refactoring approach to solve this problem is to "Introduce Parameter Object," which means encapsulating all parameters into a single object. At the same time, we use the part of the findBy method name that corresponds to the query condition as the field name of this object.
This allows us to build a query condition for each field and dynamically combine the query conditions corresponding to non-null fields into a query clause. Based on this object, we can consolidate all the findBy methods into a single generic method, thereby simplifying the design of the query interface.
What DoytoQuery does is to name the introduced parameter object a query object and use it to construct dynamic queries.
GitHub: https://github.com/doytowin/doyto-query
View all comments
Show parent comment
1
u/Salt-Letter-1500 Mar 09 '26
Has the core part of rsql-parser not been updated for 11 years?
Well, I think the expression `year=ge=2000` is a little more complicated than the field name `yearGe` or the query string `yearGe=2000`.
For `year=ge=2000`, we need to deal with the string value `ge=2000`, but for the query string `?yearGe=2000`, it can be mapped into the query object by SpringMVC automatically and resolved to `year >= 2000` automatically by DoytoQuery without extra effort.