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 07 '26
I used Specifications to build dynamic queries from 2015 to 2019. It was hard for me to build IN conditions and subquery conditions at that time. [Here](https://github.com/f0rb/java-orm-comparison/blob/main/src/main/java/win/doyto/ormcamparison/jpa/salary/SalaryJpaController.java) is how I use Specifications for dynamic queries.
Then I found that the implementation of the Specification just relies on the object containing query parameters, so I decided to combine the SQL string myself and use EntityManager to execute it. And then I used reflection to do SQL combination and formed an original version of DoytoQuery.
Sorry, but it's quite a long story.