如何使用Lombok为实体中的嵌套类成员变量分配默认值?

huangapple go评论69阅读模式
英文:

How to assign default value to the member variable of embedded class in an entity using lombok?

问题

以下是翻译好的部分:

实体类

@Entity
@Table
@Data
@Builder
class EntityClass{

  @Builder.Default
  private String someVariable = "";

  @Embedded
  private Address address;

}

嵌入类

@Embeddable
@Data
@Builder
class Address{

  @Builder.Default
  private String someVariable = "";

  @Builder.Default
  private String someOtherVariable = "";

}

对于 Address 类,默认值未生效,如果不设置值,将获得 null。

英文:

I have an embedded class in my entity. To set the default values for method variables, I've used lombok builder default. But for embedded class, it is not applying.

Entity Class

@Entity
@Table
@Data
@Builder
class EntityClass{

  @Builder.Default
  private String someVariable = "";

  @Embedded
  private Address address;

}

Embedded Class

@Embeddable
@Data
@Builder
class Address{

  @Builder.Default
  private String someVariable = "";

  @Builder.Default
  private String someOtherVariable = "";

}

For Address default values are not applying and I'm getting null if I don't set values.

答案1

得分: 2

基本上,@Builder.Default 要求赋予一个值。在正常情况下,我们通常会像这样赋值,

@Builder.Default
private String someString = "";

@Builder.Default
private Integer someInteger = 0;

同样的方式,Address 需要被初始化。

我在嵌套类中使用了构建器。

@Embedded
@Builder.Default
private Address address = Address.builder().build();

它有效!

英文:

Basically, @Builder.Default requires a value to be assigned. In normal cases, we used to assign like,

@Builder.Default
private String someString = "";

@Builder.Default
private Integer someInteger = 0;

In the same manner Address needs to be initialized.

I've used the builder in embedded class.

@Embedded
@Builder.Default
private Address address = Address.builder.build();

It works!

答案2

得分: 1

如果您使用其构建器实例化EntityClass,并在设置类型为Address的字段时使用Address.builder(),那么默认值将分配为它们的默认值。

例如:

EntityClass entity = EntityClass.builder().address(Address.builder().build()).build();
英文:

If you are instantiating the EntityClass using its builder and while setting the field with type Address, you are using Address.builder() then the default values will be assigned with their default values.

For example:

EntityClass entity = EntityClass.builder().address(Address.builder().build()).build();

huangapple
  • 本文由 发表于 2020年9月9日 00:21:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63797896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定