Video in progress

Strong Middle 🧱 OOP and SOLID

What traps do Lombok's `@Data`, `@EqualsAndHashCode` and `@ToString` set in inheritance and in entities?

By default @EqualsAndHashCode ignores the parent class's fields (callSuper = false), so different objects come out equal. @Data opens a setter on everything and destroys encapsulation. @ToString and @EqualsAndHashCode cause infinite recursion and lazy loading with bidirectional relations.

📖 Answer

The inheritance trap:

@Data class Account { private Long id; private String owner; }

@Data @EqualsAndHashCode   // callSuper = false (default)
class SavingsAccount extends Account { private BigDecimal rate; }

var a = new SavingsAccount(); a.setId(1L); a.setRate(TEN);
var b = new SavingsAccount(); b.setId(2L); b.setRate(TEN);
a.equals(b);   // true: id was not compared at all

Lombok warns about this at compile time, but warnings often get ignored. You need to set callSuper = true or give up inheritance.

Traps in entities:

  • @Data → a public setter on every field, no invariants;
  • @EqualsAndHashCode loads lazy collections, and a HashSet breaks when the ID changes after persist;
  • @ToString on order.lines → line.order → ... gives a StackOverflowError, or unexpected SQL queries when you write logs.

The rule I follow:

  • on entities, only @Getter (where needed), and I write equals/hashCode by hand;
  • @ToString(onlyExplicitlyIncluded = true) with only plain fields included;
  • for value objects and DTOs, use a record instead of Lombok.

You can enforce this at team level with settings in lombok.config such as lombok.equalsAndHashCode.callSuper = warn or lombok.data.flagUsage = warning.