I have Spring MVC + JPA applications.
I have several entities in application which Are constantly changing. I want to be able to audit this changes. I found that the
Yes, you can keep track the changes made, updated user and time-stamp.
Hibernate provides @Audited annotation to maintain entity version.
Spring provides @CreatedBy @LastModifiedBy @CreatedDate and @LastModifiedDate annotations, among these you need to provide the user name who updates using AuditorAware bean.
To enable auditing,
@EnableJpaAuditing on configuration class@Audited and @EntityListeners(AuditingEntityListener.class) on entitiesAuditorAware to provide the username@AuditedExample
@Bean
public AuditorAware createAuditorProvider() {
return () -> "username"; // should be from context/session
}
For each entities an additional table will be created to maintain version
{ENTITY_NAME}_AUD // can override the prefix and suffix of audit table nameREVINFObelow is an example of one-to-many relationship with hibernate and spring auditing
UserInfo.java
@Audited
@Entity
@EntityListeners(AuditingEntityListener.class)
public class UserInfo extends AuditInfo {
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "userInfo", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List addresses;
}
UserAddress.java
@Entity
@Audited
@EntityListeners(AuditingEntityListener.class)
public class UserAddress extends AuditInfo {
@Id
@GeneratedValue
private Long addressId;
@ManyToOne
@JoinColumn(name = "id", nullable = false)
private UserInfo userInfo;
@Column
private Long no;
@Column
private String street;
}
AuditInfo.java
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class AuditInfo {
@CreatedBy
private String createdBy;
@LastModifiedBy
private String updatedBy;
@CreatedDate
private LocalDateTime createdOn;
@LastModifiedDate
private LocalDateTime updatedOn;
}