javajpaspring-data-jpalombok

What lombok annotations are mandatory for a JPA entity


What lombok annotations are mandatory for a JPA entity, I am thinking of removing and @AllArgsConstructor. Should I remove @Data as well since I am overriding

@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)

Do I need @Data?

@Data: This generates equals, hashCode, and toString methods, which can cause issues with JPA. It's better to avoid this annotation for entities and define these methods manually or use other Lombok annotations selectively.

Entity definition

@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "foos")
public class Foo extends Bar {
..
}

Solution

  • I believe that the Lombok annotations are not mandatory for JPA entities. In fact, you should use them wisely.

    Using @Data or @EqualsAndHashCode for JPA entities is not recommended. It can cause severe performance and memory consumption issues, such as:

    You can find here what to do instead.

    @ToString can still be used, but all the lazy fields need to be excluded. This can be achieved by placing @ToString.Exclude on the desired fields, or by using @ToString(onlyExplicitlyIncluded = true) on the class and @ToString.Include on non-lazy fields.

    I personally use @Getter, @Setter, and @Accessors annotation in my JPA entities. I keep the no-arguments constructor (no need to use Lombok for that), which is mandatory for JPA entities. In addition to fluent setters (generated with Lombok), to build a new instance:

    @Getter
    @Setter
    @Accessors(chain = false)
    @Entity
    @Table(name = "foos")
    public class Foo extends Bar {
        private Strig name;
        private String description;
    }
    
    var foo = new Foo().setName("Foo").setDescription("fu fu");