Q: PrePersist and PreUpdate in Mongodb document with Spring Data JPA I have a problem using @PrePersist and @PreUpdate in Entity of MongoDB
I have a superclass that have meta field like createAt and updateAt, everything work fine if it define as @Entity, but it seem not working with @Document.
So what function i can use to work similar @PrePersist and @PreUpdate for mongo entity guys ?
This is my superclass
@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();
    }
}

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

In my application i already have @EnableJpaAuditing annotation.
EDITED:
Here is my repository for document:
public interface TestDocumentRepository extends DocumentBaseRepositoty<TestDocument> {

}

it extends from 1 superclass that we called it BaseRepository:
@NoRepositoryBean
public interface DocumentBaseRepositoty<T extends ItemDocument> extends MongoRepository<T, UUID> {

}


A: Maybe you need to use @EnableMongoAuditing (reference here) instead of EnableJpaAuditing.

A: This doesn't work as Spring Data MongoDB doesn't support JPA annotations as it's not based on JPA in the first place. Hibernate isn't involved either.
Lifecycle handling of MongoDB document entities are described in the reference documentation.

A: Solving the auditing problem the better way is to use existing mechanism for that.
Spring Data MongoDb supports @CreatedBy @CreatedDate @LastModifiedBy @LastModifiedDate annotations (Otherwise, you can use Auditable interface or convenient AbstractAuditable class). According to the documentation you have to implement just current user obtaining.
Complete documentation of auditing
