Video in progress
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;@EqualsAndHashCodeloads lazy collections, and aHashSetbreaks when the ID changes afterpersist;@ToStringonorder.lines→line.order→ ... gives aStackOverflowError, or unexpected SQL queries when you write logs.
The rule I follow:
- on entities, only
@Getter(where needed), and I writeequals/hashCodeby hand; @ToString(onlyExplicitlyIncluded = true)with only plain fields included;- for value objects and DTOs, use a
recordinstead 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.
Sign up to mark studied questions and save your progress.