Data Auditing for MongoDB

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.

@EnableMongoAuditing(modifyOnCreate=false)
public class MongoConfig extends AbstractMongoConfiguration {
 //...
}

If you prefer XML configuration, add &ltmongo:auditing... in your configuration file.

 

Implement @AuditorWare interface

It is the same interface we have discussed in the Data JPA auditing example.

@Named(value="auditor")
public class Auditor implements AuditorAware

 

 
  
 
  
  {

    @Override
    public String getCurrentAuditor() {
    return "hantsy";
    }

}


 

 

Example

Change the Conference class to the following. Add @CreatedDate, @CreatedBy, @LastModifiedDate, @LastModifidedBy to verify the auditing features.

@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;
}

Now write some codes to test it.

@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);

}

Check out the sample codes from my github.com account, https://github.com/hantsy/spring4-sandbox.

你可能感兴趣的:(spring,spring-data,auditing)