---
title: "Auditing entities in Spring Data MongoDB"
author: "study121007"
date: "2016-06-27T22:18:39Z"
tags: []
categories: ["数据库"]
slug: "auditing-entities-in-spring-data-mongodb"
draft: false
lastmod: "2016-06-27T22:25:06Z"
id: 2307618
url: "https://study121007.iteye.com/blog/2307618"
---

**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:

1. date when document has been created: [@CreatedDate](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/annotation/CreatedDate.html)
2. date when document has been updated last time: [@LastModifiedDate](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/annotation/LastModifiedDate.html)
3. user who has created document: [@CreatedBy](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/annotation/CreatedBy.html)
4. user who has done most recent update: [@LastModifiedBy](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/annotation/LastModifiedBy.html)
5. current document version: [@Version](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/annotation/Version.html)

**Configuration**

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.

```
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.2.1.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.2</version>
</dependency>
```

 In order to enable auditing we need to add **&lt;mongo:auditing/&gt;** to Spring configuration. Currently there is no way to configure it through Java Config.

```
<mongo:auditing />
<mongo:mongo id="mongo" />
<bean class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="blog-tests" />
</bean>
```

## Usage

Configuration above provides us way for auditing that includes versioning and timestamps. Example document will look like: 

```
@Document
public class Item {
    @Id
    private String id;
    @Version
    private Long version;
    @CreatedDate
    private DateTime createdAt;
    @LastModifiedDate
    private DateTime lastModified;
    ...
}
```

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:

```
@CreatedBy
private String createdBy;
@LastModifiedBy
private String lastModifiedBy;
```

Then create your implementation of [AuditorAware](http://static.springsource.org/spring-data/commons/docs/1.5.1.RELEASE/api/org/springframework/data/domain/AuditorAware.html) that will obtain current user (probably from session or Spring Security context – depends on your application):

```
public class MyAppAuditor implements AuditorAware<String> {
    @Override
    public String getCurrentAuditor() {
        // get your user name here
        return "John Doe";
    }
}
```

Last thing is to tell Spring Data MongoDB about this auditor aware class by little modification in Mongo configuration:

 

```
<mongo:auditing auditor-aware-ref="auditor" />
<bean id="auditor" class="pl.maciejwalkowiak.blog.MyAppAuditor"/>
```

 

update时好像不触发，save时会触发，此时可以使用mongoTemplate.save(S entity)，当数据存在时会执行修改操作。