Video in progress

Strong Junior 🐻 Hibernate and JPA

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:

  • toString opens the lazy collection, so a plain log line sends a hidden SELECT or throws an error outside a transaction;
  • a hashCode based on fields is mutable, which is the HashSet problem from the previous question;
  • @Data generates setters, including one for id.

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.