Search code examples
javalombok

Generating Builders for List of Nested Members in Lombok


I have a class generated by Lombok used to generate information for a Spring JDBC SimpleJdbcCall. Here's the object:

@Data
@Builder
public class DatabaseCallInformation {

    private String dbPackage;
    private String dbProcedure;
    private List<InParam> inParams;
    private List<OutParam> outParams;

    @Data
    @Builder
    public static class InParam {
        
        private String paramName;
        private int sqlType;
        private String value;

    }

    @Data
    @Builder
    public static class OutParam {
        
        private String paramName;
        private int sqlType;
        private SqlReturnType sqlReturnType;
        private RowMapper<?> rowMapper;

    }

What I want to do is be able to call the builder something like this:

    DatabaseCallInformation result = DatabaseCallInformation.builder()
        .dbPackage("MY_PACKAGE")
        .dbProcedure("MY_PROCEDURE")
        .inparam() 
            .paramName("ID")
            .sqlType(Types.NUMBER)
        .and()
        // possibly more inparams
        .outParam()
            .paramName("result")
            .sqlType(Types.VARCHAR)
        .and()
        // possibly more outParams
        .build()

(Note: the lombok classes have methods to output to a SqlParameter and SqlOutParameter which have been excluded here).

Can anyone help my get the syntax right? The inParam(), outParam(), and and() methods are now necessarily required, they are only included to try to show what I want to do.

Jason


Solution

  • DatabaseCallInformation's builder will have a method that accepts a List<InParam> and another method that accepts a List<OutParam>, so delegate to InParam's builder and OutParam's builder to build those lists. For example:

    val result = DatabaseCallInformation.builder()
        .dbPackage("MY_PACKAGE")
        .dbProcedure("MY_PROCEDURE")
        .inParams(List.of(
            InParam.builder()
            .paramName("ID1")
            ...
            .build(),
            InParam.builder()
            .paramName("ID2")
            ...
            .build()
         ))
        .outParams(List.of(
            OutParam.builder()
            .paramName("result1")
            ...
            .build(),
            InParam.builder()
            .paramName("result2")
            ...
            .build()
         ))        
         .build()