Using lomboks @Data and @Builder on entity

烂漫一生 提交于 2019-12-04 04:27:52
장재훈

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;
}

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.

In the Lombok documentation it is written: Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();

Do you use this syntax for your purpose? According to your description it's not the case, and could explain the error you get?

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:

 @RequiredArgsConstructor
 @NoArgsConstructor
 @Data
 @Builder
 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!