Skip to main content

Entities

UTURN Guides for building Hibernate Entities.

Consider providing a @Version, @CreatedDate and @LastModifiedDate

Do not use Lombok's @Data

Do not use Lombok's @Data on a Hibernate Entity, unless there is a good reason to do so and all these concerns are non-issues.

  1. Inefficient default implementation of equals(), hashCode() and toString()

By default it provides @EqualsAndHashCode. This evaluates all non-static, non-transient fields, including Lazy Loaded fields. It can cause performance problems, as it will require loading the associations, which might require DB calls. A similar problem exists for toString().

For a proper equals() and hashCode() implementation, it is not required to evaluate anything besides the id.

  1. Non-required setter generation for all fields

Fields like @Id, @Version, @CreatedDate etc. do not need setters. If those are used, it could cause serious problems. If they are not used, they clutter the API of the entity.

We should only provide setters to those fields that should actually have them, rather than making everything mutable without reason.

  1. Only a @RequiredArgs constructor

Hibernate entities require a public/protected no-args constructor. If there are no final fields, @RequiredArgs creates a no-args constructor. If a final field is added to an entities, @Data will suddenly no longer provide the appropiate constructor. We should not rely on @Data to provide a constuctor, or be aware of the risk.