Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JPA Buddy complains about @Data annotation over JPA Entity?

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.

like image 699
Georgii Vlasov Avatar asked Nov 28 '25 01:11

Georgii Vlasov


2 Answers

JPA Buddy follows best practices, and @Data for JPA entities is an antipattern... You can read more here (with some real-world examples): https://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.
like image 88
aleksey.stukalov Avatar answered Nov 30 '25 17:11

aleksey.stukalov


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

like image 35
veljkost Avatar answered Nov 30 '25 17:11

veljkost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!