gpt4 book ai didi

java - 使用 Lombok 的显式构造函数?

转载 作者:太空狗 更新时间:2023-10-29 22:55:10 25 4
gpt4 key购买 nike

我正在重写一些管理数据库的困惑代码,看到原来的程序员创建了一个映射到数据库的类,如下所示:

(我删除了在这个问题中没有意义的不必要的代码)

@Entity
@Data
@EqualsAndHashCode(callSuper = false, of = { "accessionCode", "header", "date" })
@SuppressWarnings("PMD.UnusedPrivateField")
public class PDBEntry implements Serializable {
@Id
@NaturalId
@NotEmpty
@Length(max = 4)
private String accessionCode;

@NaturalId
@NotEmpty
private Date date;

@NaturalId
// We allow for the header to be 'null'
private String header;

private Boolean isValidDssp;

@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdated = new Date(System.currentTimeMillis());

protected PDBEntry(){}

public PDBEntry(String accessionCode, String header, Date date){
this.accessionCode = accessionCode;
this.header = header;
this.date = date;
}
}

我仍然是 Hibernate 和 Lombok 的初学者,但这不会做同样的事情,Lombok 不会自动为您创建所需的构造函数吗?

@Entity
@Data
@SuppressWarnings("PMD.UnusedPrivateField")
public class PDBEntry implements Serializable {
@Id
@NaturalId
@NotEmpty
@NonNull
@Length(max = 4)
private String accessionCode;

@NaturalId
@NotEmpty
@NonNull
private Date date;

@NaturalId
// We allow for the header to be 'null'
private String header;

private Boolean isValidDssp;

@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdated = new Date(System.currentTimeMillis());
}

此外,此代码的原始程序员说他允许 header 为“空”,但他明确创建了一个需要 header 值的构造函数。我是不是遗漏了什么或者这有点矛盾?

最佳答案

看看@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor .

@Data 的构造函数行为类似于@RequiredArgsConstructor:

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared.

鉴于您的字段都不是 final@NonNull,这将导致无参数构造函数。但是,这并不是实现此行为的最具表现力的方式。

在这种情况下,您可能需要的是 @NoArgsConstructor(可选地与 @AllArgsConstructor 组合),以清楚地传达预期的行为,正如也指出的那样在文档中:

Certain java constructs, such as hibernate and the Service Provider Interface require a no-args constructor. This annotation is useful primarily in combination with either @Data or one of the other constructor generating annotations.

关于java - 使用 Lombok 的显式构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3864391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com