Search code examples
javaannotationsbuilderlombok

Lombok @Singular has no effect in child class with @Builder on Constructor


So I just discovered the Lombok @Builder annotation and I love it. Especially with the @Singular annotations for Collections.

In the case of inheritance I've read that the most effective way to create the Builder for the child class is as follows:

@Data
@AllArgsConstructor
class User {
    private String username;
    private String password;
    private String email;
}

@Data
@EqualsAndHashCode(callSuper = true)
public class Customer extends User {

    @Singular
    private List<Order> orders;

    @Builder
    public Customer(String username, String password, String email, List<Order> orders) {
        super(username, password, email);
        this.orders = orders;
    }   
}

The only problem with this approach is that the @Singular on the orders field has no effect. It is only possible to pass a List of Order to the Builder that is created, not a single order. Is there a better workaround for this situation or must I accept it the way it is?


Solution

  • You can add the @Singular annotation to the List<Order> orders parameter in the constructor of the Customer class to get the desired effect.

    @Builder
    public Customer(String username, String password, String email, @Singular List<Order> orders) {
        super(username, password, email);
        this.orders = orders;
    }