Home > Software design >  Why JPA Buddy complains about @Data annotation over JPA Entity?
Why JPA Buddy complains about @Data annotation over JPA Entity?

Time:01-20

I discovered JPA Buddy plugin for IntelliJ IDEA. In all my projects i love to use Lombok. It saves a lot of space in my entity classes. However, i just noticed, that JPA Buddy highliths it and suggest to replace.

E.g.: inspection

As a result, the @Data annotation is replaced with:

@Getter
@Setter
@ToString
@RequiredArgsConstructor
  • the hashCode and equals implementations were added:
@Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
            return false;
        }
        Project project = (Project) o;
        return id != null && Objects.equals(id, project.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

I clearly see the desription: Using @Data for JPA entities is not recommended. It can cause severe performance and memory consumption issues

But can somebody provide some real world example? From my perspective, @Data includes everything i need (equals/hashcode) as well. And i didn't notice any performance issues in my projects.

CodePudding user response:

JPA Buddy follows best practices, and @Data for JPA entities is an antipattern... You can read more here (with some real-world examples): https://www.jpa-buddy.com/blog/lombok-and-jpa-what-may-go-wrong/.

In short:

  1. According to the JPA specification, all entity classes are required to have a public or protected no-argument constructor. @Data includes only @AllArgsConstructor and not @NoArgsConstructor
  2. You can easily load attributes that are marked as Lazy due to the default @ToString method implementation provided by Lombok – which can significantly reduce the performance of your app.
  3. Finally, @EqualsAndHashCode implementation can break HashSets (and HashMaps) behavior under certain conditions.

CodePudding user response:

Have a look at this blog post, it explains what could go wrong with Lombok's generated equals() and hashCode() inside JPA entity classes and why it should be avoided

  • Related