Why @Data and @Builder Conflict in Lombok: Avoid This Common Pitfall
When @Data and @Builder are used together on a Lombok‑annotated class, the generated code can lose getters, setters, and the no‑argument constructor, leading to compilation failures; the article explains the cause and shows how to fix it with @NoArgsConstructor and @RequiredArgsConstructor.
Background
When generating a no‑argument constructor with Lombok, a teammate also added @Data and @Builder on the same class, which caused compilation to fail.
@Data annotation
@Datagenerates a no‑argument constructor, getters, setters, hashCode, toString, and equals for all fields.
@Data
public class LeaveWordReq {
@NotBlank(message = "title is required", groups = {ValidGroup.Update.class})
private String id;
@NotBlank(message = "title is required", groups = {ValidGroup.Insert.class})
@Length(min=1, max=25, message = "title length must be 1‑25", groups = {ValidGroup.Insert.class})
private String title;
}After compilation the class contains the generated getters, setters, no‑arg constructor, and overridden hashCode and toString methods.
@Builder annotation
@Buildercreates an inner static builder class that mirrors the entity’s fields and provides:
Static inner class with the same fields.
Default no‑arg constructor for the builder.
Setter‑like methods named after each field that return the builder, enabling method chaining. build() method that constructs the entity instance. toString() method for the builder.
Static builder() method in the entity to obtain a builder instance. @Builder does not generate getters, setters, or a no‑argument constructor for the entity itself.
Conflict when combined
Applying @Data and @Builder together causes Lombok to overwrite the no‑argument constructor and the getter/setter methods, leaving only the builder‑related code. The resulting class lacks the expected constructor and accessor methods, leading to compilation errors.
Resolution
Replace @Data with explicit constructor annotations to separate responsibilities:
@NoArgsConstructor
@RequiredArgsConstructor
@Builder
public class LeaveWordReq {
// fields as shown above
} @NoArgsConstructorgenerates the no‑argument constructor, @RequiredArgsConstructor generates an all‑args constructor for required fields, and @Builder provides the builder pattern without interfering with the constructors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
