In the last tutorial we saw how to use @CreatedDate and @LastModifiedDate to implement basic auditing. This tutorial shows how to use @CreatedBy and @LastModifiedBy annotations to track who created and changed an entity.
To use @CreatedBy and @LastModifiedBy annotations, we also need to implement AuditorAware<T> interface and registered it as a bean. The implementation should provide who the current user is. The generic type T specifies the type of annotated fields representing the user.
Quick Example
In following example we are using system logged in user:
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Article {
......
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
......
}
@Component
public class SystemLoggedInUserAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(System.getProperty("user.name"));
}
}
Complete Example
Entity
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Article {
@Id
@GeneratedValue
private Long id;
private String content;
@CreatedDate
private LocalDateTime dateCreated;
@LastModifiedDate
private LocalDateTime dateModified;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
.............
}
AuditorAware Implementation
@Component
public class SystemLoggedInUserAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(System.getProperty("user.name"));
}
}
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-12-13T22:47:15.216, dateModified=2018-12-13T22:47:15.216, createdBy='Joe', modifiedBy='Joe'} Article{id=1, content='modified content', dateCreated=2018-12-13T22:47:15.216, dateModified=2018-12-13T22:47:17.267, createdBy='Joe', modifiedBy='Joe'}
Example ProjectDependencies 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
|