结合 lombok @AllArgsConstructor 与 Spring-boot MongoDb @PersistenceConstructor

Combining lombok @AllArgsConstructor with Spring-boot MongoDb @PersistenceConstructor

我有一个 spring-boot 应用程序,它使用 mongoDb 数据库来存储对象。其中一个对象是 ExampleDoc,如下所示:

package com.example;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;

import org.bson.types.ObjectId;


@ToString
@Document
public class ExampleDoc {
    
    @PersistenceConstructor
    public ExmapleDoc(ObjectId id, 
            String uniqueField,
            String field1,
            String field2) {
        this.id = id;
        this.uniqueField = uniqueField;
        this.field1 = field1;
        this.field2 = field2;
    }
    

    public ExmapleDoc() {}

    @Id
    @Getter @Setter @NonNull private ObjectId id;
    @Indexed(unique = true)
    @Getter @Setter @NonNull private String uniqueField;
    @Getter @Setter String field1
    @Getter @Setter String field2
}

我正在使用 lombok 实例化字段及其 getter 和 setter。目前有 2 个构造函数,一个将所有字段作为参数,另一个不接受参数。当应用程序在数据库外部构造对象时,将使用不带参数的第二个。设置任何相关字段,然后加载文档,例如:

ExampleDoc exampleDoc = new ExampleDoc();
exampleDoc.setUniqueField("uniqueVal");
exampleDocRepository.save(exampleDoc);

持久性构造函数用于反向 - 从数据库中提取文档并将其转换为 java 对象,例如

ExampleDoc exampleDoc = exampleDocRepository.findById(objectId)

由于持久性构造函数接受所有参数,我想使用 lombok 的 @AllArgsConstructor 注释来避免必须显式添加它。

我尝试使用:

@ToString
@Document
@AllArgsConstructor
public class ExampleDoc {
    
    @PersistenceConstructor

    @Id
    @Getter @Setter @NonNull private ObjectId id;
    @Indexed(unique = true)
    @Getter @Setter @NonNull private String uniqueField;
    @Getter @Setter String field1
    @Getter @Setter String field2
}

但这没有用。有没有办法将两者结合起来,这样我就不必显式创建一个列出所有字段的构造函数?

根据https://projectlombok.org/features/constructor,要在生成的构造函数上放置注释,可以使用 onConstructor=@__({@AnnotationsHere})

所以应该是

@AllArgsConstructor(onConstructor=@__({@PersistenceConstructor}))
public class ExampleDoc {
...
}