审计意味着跟踪和记录与数据相关的事务,这只是意味着记录插入、更新和删除操作(用户和/或操作日期)。
这可以使用不同的方法来实现:
最后一个选择不需要接触我们的实体业务逻辑来添加跟踪逻辑,也不需要向实体添加额外的列或额外的表来记录更改。
如果您使用的是 Spring,则可以使用无头解决方案来跟踪您的实体。我们配置一次,随处使用:
Spring Data 提供了复杂的支持来透明地跟踪谁创建或更改了实体以及发生的时间点。(spring)
可能的方法:
1.使用标准JPA实现:
使用实体的表本身来记录更改,在这种情况下我们无法审核删除操作。
2.使用Hibernate提供的审计功能实现:
它登录到实体表以外的表,允许记录删除操作。
3.使用Spring Data JPA提供的审计功能实现:bulb::
为审计属性提供方便的注释,准备与 Spring Security 集成,也不能用于记录删除操作,因为它继承了 JPA 方法的相同缺陷。
接下来我们将介绍使用 Spring Data JPA 实现审计。
:memo: 检查点/待办事项:
1-创建 AuditorAware 将用于配置审计的实现:
导入org.springframework.data.domain.AuditorAware;导入java.util.Optional;公共 类 AuditorAwareImpl 实现 AuditorAware < String > { // 返回空而不是用户,因为我们只跟踪日期而不是用户 @Override public Optional getCurrentAuditor () { return Optional.empty(); } // 使用以下获取实际连接的用户 /* 公共用户 getCurrentAuditor() { 身份验证身份验证 = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { 返回空值; } return ((MyUserDetails) authentication.getPrincipal()).getUser(); } */ }
2-启用审计,通过将此配置类添加到spring boot项目的配置目录:
导入 org .springframework .context .annotation .Bean;导入org .springframework .context .annotation .Configuration;导入org .springframework .data .domain .AuditorAware;导入org .springframework .data .jpa .repository .config .EnableJpaAuditing; @配置@EnableJpaAuditing(auditorAwareRef = "auditorProvider" )公共类 JpaAuditingConfig { @豆 AuditorAware auditProvider() { 返回 新的 AuditorAwareImpl (); }}
3-一旦启用审计,我们创建 Auditable 类,我们将在任何我们想要的地方扩展(在我们的模型类中):
导入lombok.AllArgsConstructor;导入lombok.Data;导入lombok.NoArgsConstructor;导入org.springframework。数据。注释.CreatedDate;导入org.springframework。数据。注释.LastModifiedDate;导入org.springframework。数据.jpa.domain.support.AuditingEntityListener;导入javax.persistence.Column;导入javax.persistence.EntityListeners;导入javax.persistence.MappedSuperclass;导入java.util.Date;@Data @AllArgsConstructor @NoArgsConstructor @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class Auditable < U >{ @CreatedDate @Column(name = "created_date" ) 保护日期 createdDate; @LastModifiedDate @Column(name = "last_modified_date" ) 保护日期 lastModifiedDate; // 要跟踪修改或创建的用户,请使用 @LastModifiedBy 和 @CreatedBy //@LastModifiedBy //受保护的 U lastModifiedBy; //@CreatedBy //受保护的U createdBy;}
4-最后,从 Auditable 类扩展以跟踪更改,例如:
@Data @Entity @NoArgsConstructor @Table (name = "products" )公共类产品扩展可审核 { @Id @Column (name = "id" ) @GeneratedValue (strategy=GenerationType.AUTO) 私人长ID;}
列 created_date 和 last_modified_date 自动添加到 products 数据库中的表中,并且由于Product 类扩展 Auditable 类 createdDate 和 lastModifiedDate 属性可以以相同的方式Product 使用其他属性。
留言与评论(共有 0 条评论) “” |