5

I use project lombok and Hibernate together. I'm wondering which lombok annotation should be generally used on entity classes.

First candidate is @Data but it generates setters for all non-final fields. Since id field is not final I have setId() method which I don't want.

The second candidate is @Value but then id field is marked as final and that's why it has to be manually assigned by an application.

I could also use @Builder but it has the same issue as @Data.

To solve problem with @Data I can write my own private setter for id field to override generated one. But maybe there is a better way? What is the best practice in this case?

k13i
  • 4,011
  • 3
  • 35
  • 63

1 Answers1

0

i think you're mistaken on what @Data does. @Data combines a bunch of other annotations into one. it doesn't generate code for you. it performs annotations on code you have written.

I highly recommend reading Does the project lombok data annotation create a constructor of any kind

This link actually references the appropriate lombok data page itself.

  • What do you mean by "it doesn't generate code for you"? – k13i Mar 09 '18 at 10:10
  • i'm repeating back from your own question: First candidate is @Data **but it generates setters for all non-final fields**. Since id field is not final I have setId() method which I don't want. Annotating a class with Data doesn't generate any getters/setters. if you have written getters/setters it will automatically perform getter/setter annotation processing on them as if you had manually annotated them yourself. –  Mar 09 '18 at 10:13
  • `@Data`…bundles the features of `@ToString`, `@EqualsAndHashCode`, `@Getter` / `@Setter` and `@RequiredArgsConstructor` together: iow, `@Data` *generates* all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans: getters for all fields, setters for all non-final fields, and appropriate toString, equals and hashCode implementations that involve the fields of the class, and a constructor that initializes all final fields, as well as all non-final fields with no initializer that have been marked with `@NonNull`"-- https://projectlombok.org/features/Data – MiB May 04 '23 at 15:09