javaspringspring-data-mongodb

Why isn't my Spring Data MongoDB auditing working?


I'm using Spring Data MongoDB 1.6.0 which has an auditing feature. I put @EnableMongoAuditing above my configuration class. My bean:

@Document
public class MyBean{

@Id
private AnotherCustomBean anotherCustomBean = new AnotherCustomBean();

@CreatedDate
private Date creationDate;

@LastModifiedDate
private Date lastModifiedDate;

...

When I save this bean with mongoTemplate.save(myBean); it's not setting the created- and last modified date. It has no errors.


Solution

  • The problem was the @Id annotation. To use Spring auditing define an ObjectId (null for new saved objects), that's how Spring decides on @LastModifiedDate and @CreatedDate.

    Use custom beans on @Id by implementing Auditable<String,String>.

    By Felby:

    I found that the @Id field needed to be null at the time of save() only for the @CreatedDate and @CreatedBy annotations. The @LastModifiedDate and @LastModifiedBy fields worked regardless of whether the @Id field was initialized or not.