Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb auditing not working.. (Java config)

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.

like image 344
Sercan Ozdemir Avatar asked Nov 04 '14 06:11

Sercan Ozdemir


People also ask

How do I enable auditing in MongoDB?

To enable auditing in MongoDB Enterprise, set an audit output destination with --auditDestination .

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Which is better MongoTemplate or MongoRepository?

MongoTemplate is a bit more lower level where you need to write your own queries. With embedded documents and denormalization it can be easier to write complex queries with MongoTemplate. For simple things I would use MongoRepository. I've seen some examples where both are used together in a hybrid approach.

Can I use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.


Video Answer


1 Answers

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.

like image 157
Sercan Ozdemir Avatar answered Oct 06 '22 09:10

Sercan Ozdemir