JPA的审计(Auditing)功能允许开发人员跟踪实体的创建时间
、修改时间
以及创建者
、修改者
等信息,以便进行数据审计
和追踪变更历史
。通过使用JPA的审计功能,可以在实体类中自动记录这些审计信息,而无需手动处理。
代码如下:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String updatedBy;
}
在这个示例中,定义了一个User实体类,其中使用了Spring Data JPA提供的注解来实现审计功能。@CreatedDate
和@LastModifiedDate
注解用于自动记录创建时间和修改时间;@CreatedBy
和@LastModifiedBy
注解用于记录创建者和修改者。
在保存或更新User对象时,JPA会自动填充这些审计信息。可以通过配置实现自定义的审计信息填充逻辑,比如从当前登录用户中获取创建者和修改者信息
等。
代码如下:
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
public class CustomAuditor implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
// 这里可以添加自定义逻辑来返回当前的审计人员,比如从当前登录用户中获取
return Optional.of("Custom Auditor");
}
}
然后,在应用程序配置类中,将这个 CustomAuditor 类注册为审计信息提供者:
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@Configuration
@EnableJpaAuditing(auditorAwareRef = "customAuditor")
public class JpaConfig {
@Bean
public AuditorAware<String> customAuditor() {
return new CustomAuditor();
}
}