'How to enable auditing for MongoDB via Annotations in Spring
I wanted to enable some auditing features, such as @CreatedDate. I am not using Spring xml configuration file, so I cannot add mongo:auditing to Spring configuration. I was wondering if there was an alternative way of enable auditing. The following code is the model for user. But whenever I create a user, the date is not stored in the document, so the auditing it's not working. Could someone give me some help?
@Document(collection = "user")
public class User {
@Id
private String id;
@Indexed(unique = true)
private String email;
private String name;
@CreatedDate
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Solution 1:[1]
Because you are not using configuration via XML, I believe you are using annotations. You own a class like this:
public class MongoConfig extends AbstractMongoConfiguration {...}
Thus, in addition to the annotations you should already have, add: @EnableMongoAuditing
Your configuration class will look like this now:
@Configuration
@EnableMongoRepositories(basePackages="...")
@EnableMongoAuditing
public class MongoConfig extends AbstractMongoConfiguration {...}
I hope this helps!
Solution 2:[2]
That's all you need. No subclasses or other stuff.
@Configuration
@EnableMongoAuditing
public class AnyConfig {}
Solution 3:[3]
You should write a configuration class in which you can connect to MongoDB database using mongoClient by passing db url. and add the anootaion of @EnableMongoAuditing on top of that class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | araujodavid |
Solution 2 | Drew Wills |
Solution 3 |