Close

Spring Data JPA - Implementing Basic Auditing by using @CreatedDate and @LastModifiedDate

[Last Updated: Nov 27, 2018]

Spring Data provides following annotations to keep track of who created or changed an entity and when the change happened.

  • @CreatedDate
  • @LastModifiedDate
  • @CreatedBy
  • @LastModifiedBy

This example shows the use of first two annotations. We have to do following things:

  1. In entity class, create date fields and annotate them with @CreatedDate and @LastModifiedDate. The types of these fields can be type Joda-Time, DateTime, legacy Java Date and Calendar, JDK8 date and time types, and long or Long.
  2. Use following on our entity class.
    @EntityListeners(AuditingEntityListener.class)
    @EntityListeners is JPA specific annotation.
    AuditingEntityListener.class is Spring Data specific class which implements the listener to capture auditing information on persisting and updating entities.
  3. Annotate our configuration class with @EnableJpaAuditing which enables annotation based auditing.
  4. Also we need to add following extra dependency to activate auditing functionality:
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>5.1.3.RELEASE</version>
     </dependency>

Example

Entity

package com.logicbig.example;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.LocalDateTime;

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Article {
    @Id
    @GeneratedValue
    private Long id;
    private String content;
    @CreatedDate
    private LocalDateTime dateCreated;
    @LastModifiedDate
    private LocalDateTime dateModified;
    .............
}

Repository

public interface ArticleRepository extends CrudRepository<Article, Long> {
}

Java Config

@EnableJpaRepositories
@EnableJpaAuditing
@ComponentScan
@Configuration
public class AppConfig {

    @Bean
    EntityManagerFactory entityManagerFactory() {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("example-unit");
        return emf;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

Example client

@Component
public class ExampleClient {
    @Autowired
    private ArticleRepository repo;

    public void run() {
        //creating and persisting an Article
        Article article = new Article("test article");
        repo.save(article);

        //load article
        Optional<Article> optArticle = repo.findById(article.getId());
        Article loadedArticle = optArticle.get();
        System.out.println(optArticle.get());

        //have some delay to see a clear diff in modified time
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //modify article
        loadedArticle.setContent("modified content");
        repo.save(loadedArticle);

        //load again
        System.out.println(repo.findById(loadedArticle.getId()).get());
    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);
        ExampleClient exampleClient = context.getBean(ExampleClient.class);
        exampleClient.run();
        EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
        emf.close();
    }
}
Article{id=1, content='test article', dateCreated=2018-11-27T23:51:36.461, dateModified=2018-11-27T23:51:36.461}
Article{id=1, content='modified content', dateCreated=2018-11-27T23:51:36.461, dateModified=2018-11-27T23:51:38.516}

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.1.3.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-context version 5.1.3.RELEASE
  • spring-aspects 5.1.3.RELEASE: Spring Aspects.
  • hibernate-core 5.3.7.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • h2 1.4.197: H2 Database Engine.
  • JDK 1.8
  • Maven 3.5.4

Spring Data JPA basic auditing Select All Download
  • spring-data-jpa-annotation-based-auditing
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Article.java
          • resources
            • META-INF

    See Also