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

标签 java hibernate lombok

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

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

@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/

相关文章:

java - Sonarqube - 使用 Lombok @data 删除此未使用的私有(private)字段 Code Smell

java - Lombok @Synchronized 与 Mockito 抛出 NPE

java - ElasticSearch JavaAPI RestClient 未给出响应

java - 实现基于枚举的单例

java - 如何在Lucene中搜索特定范围内的术语

sql - 如何使用 hibernate 记录最终的 SQL 查询

java - 如果外键引用空行而键不可为空,如何不崩溃?

java - 一对多映射

java - jpa插入行时应返回用于主键列的序列号

intellij-idea - 使用 Lombok 的 @Slf4j 和 Intellij 进行构建 : Cannot find symbol log