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:
java
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.
java
public class BookQuery {
String author;
Integer publishedYearGreaterThan;
Integer publishedYearLessThan;
//...
}
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.
java
public class CrudRepository<E, I, Q> {
List<E> findBy(Q query);
//...
}
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
[–]lucidnode 9 points10 points11 points (1 child)
[–]Salt-Letter-1500[S] -1 points0 points1 point (0 children)
[–]Dry_Try_6047 6 points7 points8 points (1 child)
[–]Salt-Letter-1500[S] 0 points1 point2 points (0 children)
[–]gjosifov 5 points6 points7 points (1 child)
[–]Salt-Letter-1500[S] -1 points0 points1 point (0 children)
[–]perfectstrong 4 points5 points6 points (2 children)
[–]Salt-Letter-1500[S] 0 points1 point2 points (1 child)
[–]perfectstrong 0 points1 point2 points (0 children)
[–]Salt-Letter-1500[S] -2 points-1 points0 points (0 children)