Mongodb 文档中的 PrePersist 和 PreUpdate 以及 Spring Data JPA

PrePersist and PreUpdate in Mongodb document with Spring Data JPA

我在 MongoDB 的实体中使用 @PrePersist@PreUpdate 时遇到问题 我有一个超类,它有像 createAt 和 updateAt 这样的元字段,如果它定义为 @Entity,一切正常,但它似乎不适用于 @Document。 那么我可以使用什么功能来为 mongo 实体人员提供类似 @PrePersist@PreUpdate 的工作? 这是我的超类

@EntityListeners(AuditingEntityListener.class)
public class ItemDocument implements Serializable {

    private static final long serialVersionUID = 5894122627332059602L;

    @Id
    private UUID id;
    @Field("created_at")
    @CreatedDate
    private long created_at;
    @Field("created_by")
    private String created_by;
    @Field("updated_at")
    @LastModifiedDate
    private long updated_at;
    @Field("updated_by")
    private String updated_by;

    @PrePersist
    protected void onPersist() {
        this.created_at = new Date().getTime();
        this.updated_at = this.created_at;
    }

    /**
     * On update.
     */
    @PreUpdate
    protected void onUpdate() {
        this.updated_at = new Date().getTime();
    }
}

这是我的实体

@Document(collection = "test_entity")
public class TestDocument extends ItemDocument {
    @Field("test_field")
    private String testField;
    @Field("test_field_2")
    private String testField2;
}

在我的应用程序中,我已经有 @EnableJpaAuditing 注释。

已编辑: 这是我的文档存储库:

public interface TestDocumentRepository extends DocumentBaseRepositoty<TestDocument> {

}

它从我们称之为 BaseRepository 的 1 个超类扩展而来:

@NoRepositoryBean
public interface DocumentBaseRepositoty<T extends ItemDocument> extends MongoRepository<T, UUID> {

}

也许您需要使用 @EnableMongoAuditing (reference here) 而不是 EnableJpaAuditing

这不起作用,因为 Spring 数据 MongoDB 不支持 JPA 注释,因为它首先不基于 JPA。 Hibernate 也不参与。

MongoDB 文档实体的生命周期处理在 reference documentation 中进行了描述。

解决审计问题的更好方法是使用现有机制。

Spring 数据MongoDb 支持@CreatedBy @CreatedDate @LastModifiedBy @LastModifiedDate 注解(否则,可以使用Auditable 接口或方便的AbstractAuditable class)。根据文档,您必须仅实现当前用户获取。

Complete documentation of auditing