Video in progress

Strong Middle 🧭 Design patterns

What problems come up when you put Lombok's `@Builder` on a JPA entity?

@Builder generates an all-args constructor and removes the no-args constructor, which Hibernate needs. On top of that, the builder leaves collection fields as null and ignores default values set on fields.

📖 Answer

The first error shows up immediately: Hibernate creates the entity through reflection using a no-args constructor. With @Builder alone, Lombok generates only a package-private all-args constructor, and on a query you get No default constructor for entity. People add @NoArgsConstructor @AllArgsConstructor and move on to the next problems.

The second one works silently:

@Entity
@Builder @NoArgsConstructor @AllArgsConstructor
public class Order {
    @Id @GeneratedValue Long id;
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private List<OrderLine> lines = new ArrayList<>();
    private OrderStatus status = OrderStatus.NEW;
}

Order o = Order.builder().build();
o.getLines().add(line); // NPE — lines is null
// status is null too, not NEW

The builder doesn't see field initializers. Adding @Builder.Default fixes it, but it's easy to forget.

The third one is a design issue. The builder also exposes fields like id and version; someone writes .id(5L), calls merge, and overwrites a different row.

I don't use a builder for entities. Instead I use a meaningful constructor or a static factory: Order.create(customer, lines), which checks the invariants and initializes the collection. A builder is very handy for DTOs, records and test fixtures.