@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.
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
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.