Monday, March 10, 2014

How to set CreatedBy, CreatedDate, UpdatedBy, UpdatedDate and Version Audit entities for MongoDB documents?

It is a common programming practice to have audit fields associated with each document which helps in determine the basic information like when document was last created or modified and who did it. This information proves to be very crucial piece of information available while troubleshooting a problem.
Stamping each document with these information in different collections becomes tedious and repetitive. This topic covers how can we use Spring framework to auto populate these fields and developers just need to focus on the other important fields within a document.

A little background... 

We will use Spring Data MongoDB in the example to integrate with MongoDB. MongoDB is a scalable, high-performance, Document Oriented NoSQL database. 
A model can be made Auditable by one of the following ways:
1. Using @CreatedBy, @CreatedDate@LastModifiedBy, @LastModifiedDate and @Version annotations defined in package org.springframework.data.annotation.
2. Model implementing org.springframework.data.domain.Auditable interface. Auditable is an interface that defines all required properties for auditing an Entity, it is inherited from Presistable interface.
In this article we will focus on using Annotations for populating the audit fields.


Figure: Class diagram for Audit Entity