Spring Data访问Elasticsearch----Elasticsearch审计Auditing-一、准备实体

时间:2024-03-20 17:32:37

为了让审计代码能够判断一个实体实例是否是新的,实体必须实现Persistable<ID>接口,定义如下:

package org.springframework.data.domain;

import org.springframework.lang.Nullable;

public interface Persistable<ID> {
    @Nullable
    ID getId();

    boolean isNew();
}

由于Id的存在并不是确定Elasticsearch中是否有新特征的充分标准,因此需要额外的信息。一种方法是使用与创建相关的审核字段来进行此决策:
Person实体可能如下所示——为了简洁起见,省略了getter和setter方法:

@Document(indexName = "person")
public class Person implements Persistable<Long> {
    @Id private Long id;
    private String lastName;
    private String firstName;
    @CreatedDate
    @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
    private Instant createdDate;
    @CreatedBy
    private String createdBy
    @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
    @LastModifiedDate
    private Instant lastModifiedDate;
    @LastModifiedBy
    private String lastModifiedBy;

    public Long getId() {                                                --------1 
        return id;
    }

    @Override
    public boolean isNew() {
        return id == null || (createdDate == null && createdBy == null); --------2 
    }
}

1. getter是接口所需的实现,
2. 如果对象没有id或没有设置包含创建属性的字段,则该对象为新对象。