带有 Spring Data JPA 的 Mongodb 文档中的 PrePersist 和 PreUpdate

red*_*oxx 1 java spring mongodb spring-data spring-data-mongodb

我有使用问题@PrePersist,并@PreUpdate在MongoDB中我的实体有有像createAt和updateAt,一切都做工精细元场,如果它定义了一个超类@Entity,但它似乎不工作@Document。那么,什么功能,我可以使用类似的工作,@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的实体

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

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

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

public interface TestDocumentRepository extends DocumentBaseRepositoty<TestDocument> {

}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

Lor*_*ore 5

也许您需要使用@EnableMongoAuditing参考此处)而不是EnableJpaAuditing.