#Data Auditing for MongoDB
Like the JPA auditing provided in Spring Data JPA project, in the latest Spring Data MongoDB, it provides the same feature for MongoDB. You can mark the same annotations(@CreatedDate
, @CreatedBy
, @LastModifiedDate
, @LastModifidedBy
) on your Mongo @Document
class and make these fields be filled automatically at runtime.
Enable Auditing
Add @EnableMongoAuditing
on your @Configuration
class if you are using Java config.
<pre> @EnableMongoAuditing(modifyOnCreate=false) public class MongoConfig extends AbstractMongoConfiguration { //... } </pre>
If you prefer XML configuration, add <mongo:auditing...
in your configuration file.
<pre> <mongo:auditing auditor-aware-ref="auditor" modify-on-creation="false"/> </pre>
Implement @AuditorWare
interface
It is the same interface we have discussed in the Data JPA auditing example.
<pre> @Named(value="auditor") public class Auditor implements AuditorAware<String> { @Override public String getCurrentAuditor() { return "hantsy"; } } </pre>
Example
Change the Conference
class to the following. Add @CreatedDate
, @CreatedBy
, @LastModifiedDate
, @LastModifidedBy
to verify the auditing features.
<pre> @Document public class Conference { @Id private String id; @NotNull private String name; @NotNull private String description; @CreatedBy private String createdBy; @CreatedDate private Date createdDate; @LastModifiedBy private String lastModifiedBy; @LastModifiedDate private Date lastmodifiedDate; } </pre>
Now write some codes to test it.
<pre> @Test public void retrieveConference() { Conference conference = newConference(); conference = conferenceRepository.save(conference); assertTrue(null != conference.getId()); conference = conferenceRepository.findByName("JUD2013"); assertTrue(null != conference); assertTrue("hantsy".equals(conference.getCreatedBy())); assertTrue(conference.getCreatedDate()!=null); log.debug("conference.getLastModifiedBy()@"+conference.getLastModifiedBy()); log.debug("conference.getLastmodifiedDate()@"+conference.getLastmodifiedDate()); assertTrue(conference.getLastModifiedBy()==null); assertTrue(conference.getLastmodifiedDate()==null); conference.setName("test"); conference=conferenceRepository.save(conference); assertTrue("test".equals(conference.getName())); assertTrue(conference.getLastModifiedBy()!=null); assertTrue(conference.getLastmodifiedDate()!=null); } </pre>
Check out the sample codes from my github.com account, .