Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lomboks @Data and @Builder on entity

Tags:

java

lombok

I am using the following:

@Entity
@Data
@Builder
@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 new ... the builder() works.

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

like image 639
Jan Galinski Avatar asked Nov 09 '16 21:11

Jan Galinski


2 Answers

try this code with lombok version 1.16.18 over :

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class User {
    private String id;
    private String firstName;
    private String lastName;
}
like image 80
장재훈 Avatar answered Sep 18 '22 17:09

장재훈


Beware of that data objects aren't entities! Simply put, there is problem with hashcode/equals (when it considers id fields) and also toString method with lazy loaded parts of entity. For reference you can check Vlad Mihalceas article.

You should:

  • exclude id fields from hashcode/equals
  • exclude association fields which are not managed in given entity from hashcode/equals
  • exclude all lazy loaded fields from toString method
  • exclude fields possibly causing circular references from toString method

For sure read at least something on topic of how does JPA do "dirty checking" before beeing confident that your handwritten or generated equals/hashcode method is ok.

like image 29
Lubo Avatar answered Sep 21 '22 17:09

Lubo