Spring data mongodb auditing not working.. (Java c

2019-02-12 15:41发布

问题:

i'm currently using Spring data mongodb 1.6.0-RELEASE and i know it has auditing feature. I put @EnableMongoAuditing annotation on top of my configuration class. And my bean is below:

@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 created date and last modified date...And it has no errors.

Any help would be appreciated,

Thanks.

回答1:

The actual problem was the @Id annotation. To use spring auditing properly, you have to define an ObjectId (null for new saved objects), thats how spring decide @LastModifiedDate and @CreatedDate

Afterwards, i found a way to make it possible use custom beans on @Id by implementing Auditable<String,String>

Thanks to @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.



回答2:

I don't know exactly, but try to add joda-time to classpath to use date-related audit annotations

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.2</version>
</dependency>