Jan Galinski Jan Galinski - 2 months ago 34
Java Question

Using lomboks @Data and @Builder on entity

I am using the following:

@NoArgsConstructor(force = true)
public class User {
private String id;
private String firstName;
private String lastName;

what I want to achieve: for JPA usage, I need a POJO with noArgConstructor, getters/setters and equals/hashCode/toString.

For instance creation (for example in tests) I want to use User.builder().build();

Problem: it does not compile, there seems to be an issue with the NoArgConstructor vs. RequiredFieldsConstructor:

Error:(15, 1) java: constructor User in class x.y.z.User cannot be applied to given types;
required: no arguments
found: java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String
reason: actual and formal argument lists differ in length

Update: The error occurs when I try to create a new entity via
... the builder() works.

What do I miss? Isn't it possible to use @Data, @Entity and @Builder at the same time?


I will answer my own question by summerizing the comments.

First of all, thanks to @RoelSpilker, you can use Builder and Data together on one Pojo if you explicitly provide AllArgs- and NoArgs- constructors:

 public class Person {...}

But: the builder created for this class will not know any inherited fields. For my use case (having some AbstractEntities) this renders the solution useless and I will stick with manual helpers/builders for now.