I am using JPA alongside hibernate envers to audit the entities. I want to all the entities have creation_date and modification_date table . As result , I created base class which contains the createdBy and lastModificationDate , and all the project entities extends this class .
@MappedSuperclass
@Data
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractEntity implements Serializable {
@JsonIgnore
@Column(name = "creation_date", nullable = false , updatable = false)
@CreatedDate
private LocalDateTime creationDate;
@JsonIgnore
@Column(name = "modification_date")
@LastModifiedDate
private LocalDateTime modificationDate;
@Column(name = "created_by")
private String createdBy;
@Column(name = "modified_by")
private String modifiedBy;
@PrePersist
public void prePersist() {
this.creationDate = LocalDateTime.now();
}
@PreUpdate
public void preUpdate() {
this.modificationDate = LocalDateTime.now();
}
}
however ,@CreatedBy and @LastModificationDate are not working without setting their values inside @PrePersist and @PreUpdate .
@PrePersist
public void prePersist() {
this.creationDate = LocalDateTime.now();
}
@PreUpdate
public void preUpdate() {
this.modificationDate = LocalDateTime.now();
}
}
if I commented @PreUpdate and @PrePersist annotation with their functions . they creationDate and modificationDate values will be null in original entities .
On the other hand , creationDate and modificationDate values are always with null in the audit table
Customer Entity
@Entity
@Table(name = "customer")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
@Builder
@Audited
@EntityListeners(AuditingEntityListener.class)
public class Customer extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
private String exmaple;
private String example2;
}
AuditConfig
package com.sympl.customer.common.config.advice;
import com.sympl.customer.common.config.AuditorAwareImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing(auditorAwareRef = "auditorProvider" , dateTimeProviderRef = "auditingDateTimeProvider")
public class AuditConfig {
//...
@Bean
AuditorAware<String> auditorProvider() {
return new AuditorAwareImpl();
}
//...
}
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.4.30.Final</version>
</dependency>
I followed the baeldung tutorial to setup audit
.I googled on similar issues , but their solution doesn't work with me