在实体上使用lomboks @Data和@Builder [英] Using lomboks @Data and @Builder on entity

查看:340
本文介绍了在实体上使用lomboks @Data和@Builder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下内容:

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

我想要实现的目标:对于JPA用法,我需要一个带有noArgConstructor的POJO ,getters / setters和equals / hashCode / toString。

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

例如创建(例如在测试中)我想使用User.builder()。build();

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

问题:它没有编译,NoArgConstructor与RequiredFieldsConstructor似乎存在问题:

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

更新:当我尝试创建一个错误时发生错误新实体通过 new ...构建器()工作。

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

我想念什么?是不是可以同时使用@ Data,@ Entity和@Builder?

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.

首先,感谢@RoelSpilker,如果明确提供AllArgs-和NoArgs-构造函数,可以在一个Pojo上同时使用Builder和Data :

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 {...}

但是:为此类创建的构建器不会知道任何继承的字段。对于我的用例(有一些AbstractEntities),这使得解决方案无用,我现在将坚持使用手动助手/构建器。

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.

这篇关于在实体上使用lomboks @Data和@Builder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆