Video in progress
What problems come up if you put Lombok's @Data on entities?
@Data generates equals, hashCode and toString over all fields. With a bidirectional association this leads to StackOverflowError, and with lazy fields it leads to unexpected SELECTs or LazyInitializationException.
📖 Answer
The classic case: Department and Employee reference each other.
@Data @Entity
class Department {
@Id Long id;
@OneToMany(mappedBy = "department") List<Employee> employees;
}
@Data @Entity
class Employee {
@Id Long id;
@ManyToOne Department department;
}
With log.info("{}", employee), toString calls department, which calls employees, which call department again... and you get StackOverflowError. hashCode loops the same way.
Less obvious problems:
toStringopens the lazy collection, so a plain log line sends a hidden SELECT or throws an error outside a transaction;- a
hashCodebased on fields is mutable, which is theHashSetproblem from the previous question; @Datagenerates setters, including one forid.
On entities I use only @Getter, @Setter where needed, and @NoArgsConstructor(access = PROTECTED). If I need toString, I use @ToString(onlyExplicitlyIncluded = true) and add only simple fields with @ToString.Include. I write equals/hashCode by hand.
Sign up to mark studied questions and save your progress.