• Subscribe
  • Are you tired of writing boilerplate code when building dynamic SQL queries? Check my idea!

    Forb Yuan
    0 replies
    Suppose I need to build a dynamic WHERE clause:
    StringJoiner sql = new StringJoiner(" AND ", "WHERE", "");
    List<Object> args = new ArrayList<>();
    if (ageGt != null) {
        sql.add("age > ?");
        args.add(ageGt);
    }
    if (ageGe != null) {
        sql.add("age >= ?");
        args.add(ageGe);
    }
    if (ageLt != null) {
        sql.add("age < ?");
        args.add(ageLt);
    }
    // ...
    return sql.toString();
    
    There will be more and more if statements to meet new requirements and all the if statements share the same structure: check if the value is not null and append the query condition if true. It's kinda boilerplate and also a signal for refactoring code in software engineering. We just put the parameters together as the article said and build the SQL in the reflection way will save me a lot of time to write the IFs.
    public class UserQuery {
      private Integer ageGt;  // age > ?
      private Integer ageGe;  // age >= ? 
      private Integer ageLt;  // age < ?
    }
    
    Now we just need to define the fields by combining the column name and the operator suffix in the UserQuery, then the tool generates the WHERE clause for the assigned fields. Here is a Java implementation, feedback is welcome: https://github.com/doytowin/doyto-query
    🤔
    No comments yet be the first to help