Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using Builder for a subset of the parameters

@Entity
@Data
@NoArgsConstructor
@Builder
public class Technology {

    @Id
    private UUID uuid;

    private String name;
}

in this case when I need to create the object I need to do this:

Technology t = Technology.builder()
        .uuid(UUID.randomUUID())
        .name("tName")
        .build()

what I would like to do is to only create it like this:

Technology t = Technology.builder()
        .name("tName")
        .build()

and having the Technology constructor handle the generation of the UUID.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My understanding is that Builder uses the @AllArgsConstructor to initialize the object but is there no way of using a subset of the parameters?

I tried to write my own constructor

public Technology(String name) {
    uuid = UUID.randomUUID();
    this.name = name;
}

but then when I try to use the builder like this:

Technology t = Technology.builder()
    .name("tName")
    .build()

it complains about not having set the uuid

>Solution :

That is not an issue with Lombok builder. Lombok initialises default empty values (null for objects, 0 for numeric primitives) for all unassigned fields when creating a new instance. So, your second option works from Lombok POV. Your UUID will be null. But since it’s a @Id, that is not allowed to have null in that field. You have to assign it to something – or define an auto generation policy.

BTW, having a builder on a class with only 2 fields seems like a premature optimisation to me. I much rather stick to your single-argument constructor – it should do all you need.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading