Auditing entities in Spring Data MongoDB
Spring Data MongoDB 1.2.0 silently introduced new feature: support for basic auditing. Because you will not find too much about it in official reference in this post I will show what benefits does it bring, how to configure Spring for auditing and how to annotate your documents to make them auditable.
Auditing let you declaratively tell Spring to store:
- date when document has been created: @CreatedDate
- date when document has been updated last time: @LastModifiedDate
- user who has created document: @CreatedBy
- user who has done most recent update: @LastModifiedBy
- current document version: @Version
First of all Maven dependencies to latest Spring Data MongoDB and Spring Data Commons. Additionally in order to use date-related audit annotations we need to add joda-time to classpath.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In order to enable auditing we need to add <mongo:auditing/> to Spring configuration. Currently there is no way to configure it through Java Config.
1 2 3 4 5 6 7 8
Configuration above provides us way for auditing that includes versioning and timestamps. Example document will look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Now you can save document using MongoTemplate or your repository and all annotated fields are automagically set.
As you have probably noticed I did not use here user related annotations @CreatedBy and @LastModifiedBy. In order to use them we need to tell Spring who is a current user.
First add user related fields to your audited class:
1 2 3 4 5
Then create your implementation of AuditorAware that will obtain current user (probably from session or Spring Security context – depends on your application):
1 2 3 4 5 6 7 8
Last thing is to tell Spring Data MongoDB about this auditor aware class by little modification in Mongo configuration: