2

I am using spring annotations @CreatedBy for createdBy and @LastModifiedBy for updatedBy-

@CreatedBy
@Field(value = "createdBy")
private String createdBy;

@LastModifiedBy
@Field(value = "updatedBy")
private String updatedBy; 

Also i have used @EnableMongoAuditing this annotation in the main application.

And created a class which implements AuditorAware like below-

@Component
public class UserAudtiting implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {

        String uname = SecurityContextHolder.getContext().getAuthentication().getName();
        return Optional.of(uname);
    }
}

So when i am using some post method to save data , I am getting "createdBy":null in response.

What should i do for this? Please help!

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
Sonal
  • 345
  • 1
  • 4
  • 8

2 Answers2

2

As specified in the documentation,

First, note that only entities that have a @Version annotated field can be audited for creation (otherwise the framework will interpret a creation as an update).

Add @Version in your entity.

Moshe perez
  • 1,626
  • 1
  • 8
  • 17
Madhu Tomy
  • 662
  • 11
  • 25
1

In order to enable auditing we need to add to Spring configuration. XML or JAVA Config, either way

Spring XML Configuraton

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

Spring Java Configuration

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.abc")
@EnableMongoRepositories(basePackages = "com.abc.xyz.repository")
@EnableMongoAuditing
public class MongoApplicationConfiguration {

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
        MongoCredential mongoCredential = MongoCredential.createCredential("user", "test", "samp".toCharArray());
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return new SimpleMongoDbFactory(mongoClient, "test");
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

In order to use @CreatedBy and @LastModifiedBy you 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 that will obtain current user (probably from session or Spring Security context – depends on your application):

public class UserAudtiting implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {
      // get your user name here
      String uname = SecurityContextHolder.getContext().getAuthentication().getName();
      return Optional.of(uname);
    }
}

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="app.demo.UserAudtiting "/>

More details here: https://www.javacodegeeks.com/2013/05/auditing-entities-in-spring-data-mongodb.html

Mebin Joe
  • 2,172
  • 4
  • 16
  • 22
  • I am using spring maven project.So where should i add spring configuration? in pom.xml? – Sonal Mar 29 '19 at 09:53
  • @Sonal Which version of Spring are you using? You can do either way, using XML as mentioned above or Java way. Will Update the answer. Please give it a try and hope it works. Let me know in case if you face any issues. – Mebin Joe Apr 01 '19 at 05:17
  • I am using spring boot model version- 4.0.0 and version-2.1.1 release. And I am getting an error in pom.xml while using spring configuration as mentioned above. – Sonal Apr 01 '19 at 11:11
  • @Sonal Error in pom.xml? So you tried Spring Java config or Spring XML config ? – Mebin Joe Apr 01 '19 at 11:17
  • I tried it in Spring xml config still getting error.Can you please help me out regarding this ! – Sonal Apr 01 '19 at 11:27
  • @Sonal Just create a new java config class and copy-paste the above Spring Java Configuration described in the answer with your parameters. – Mebin Joe Apr 01 '19 at 11:29
  • I have already created mongo credentials.What should i do then? – Sonal Apr 01 '19 at 11:40
  • @Sonal. Then skip that part and autowire mongo like `@Autowired private Mongo mongo;` – Mebin Joe Apr 01 '19 at 11:44
  • Where should i pass mongo object? Because when i skip that line i am getting error below that line and goes on. – Sonal Apr 01 '19 at 12:20
  • @Sonal Let's make it minimal and simple. Add this in your newly created config class. `@Configuration @EnableMongoAuditing public class MongoApplicationConfiguration {}` – Mebin Joe Apr 01 '19 at 12:24
  • @Sonal What is the issue you facing. Please debug and ensure nothing is null or breaking. – Mebin Joe Apr 03 '19 at 06:47