Auditing翻译过来是审计和审核。Spring的优秀之处在于帮我们想到了很多我们平时烦琐事情的解决方案,我们在实际的业务系统
中,针对一张表的操作大部分是需要记录谁什么时间创建的,谁什么时间修改的,并且能让我们方便地记录操作日志。Spring Data JPA为我们提供了审计功能的架构实现,提供了4个注解专门解决这件事:
- @CreatedBy:创建人。
- @CreatedDate:创建时间。
- @LastModifiedBy:最后修改人。
- @LastModifiedDate:最后修改时间。
增加公共虚拟类
一般情况下,创建人、创建时间、最后修改人、最后修改时间四个字段都是统一的。所以,我们可以将其提取到公共的类中,然后所有的实体类继承这个虚拟类。
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class AbstractAuditable {
@CreatedBy
private String createBy;
@CreatedDate
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.sql.Timestamp createTime;
@LastModifiedBy
private String updateBy;
@LastModifiedDate
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.sql.Timestamp updateTime;
}
[tag type="default"]必须添加@MappedSuperclass
注解[/tag]
修改实体,继承AbstractAuditable
@Entity
@Table(name = "sys_user")
@Data
@Slf4j
public class SysUser extends AbstractAuditable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@JoinColumn(name = "dept_id", referencedColumnName = "dept_id")
@ManyToOne(cascade = CascadeType.ALL)
private SysDept sysDept;
private String userName;
private String nickName;
private String userType;
private String email;
@Column(name = "phonenumber")
private String phoneNumber;
private String sex;
private String avatar;
@JsonIgnore
private String password;
@Enumerated(EnumType.STRING)
private Status status;
private String delFlag;
private String loginIp;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.sql.Timestamp loginDate;
private String remark;
private Long recycleCompanyId;
private Long medicalInstitutionId;
private Long ethnicity;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "sys_user_role",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id")})
private Set<SysRole> sysRoles;
}
实现AbstractAuditable接口
实现AbstractAuditable
接口,提供创建者、最后修改者信息,这里我们随便模拟了以下常量。
public class MyAuditorAware implements AuditorAware<String> {
/**
* Returns the current auditor of the application.
*
* @return the current auditor.
*/
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of("测试用户");
}
}
开启Auditing功能
通过@EnableJpaAuditing注解开启JPA的Auditing功能,并且告诉应用AuditorAware的实现类是谁。
@SpringBootApplication
@EnableJpaRepositories(queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND)
@EnableJpaAuditing
public class Example1Application {
public static void main(String[] args) {
SpringApplication.run(Example1Application.class, args);
}
@Bean
public AuditorAware<String> auditorAware(){
return new MyAuditorAware();
}
}
测试
@GetMapping("/save")
public Long save(){
SysUser sysUser = new SysUser();
sysUser.setNickName("测试123321");
sysUser.setUserName("测试123321");
sysUser.setSex("0");
sysUserRepository.save(sysUser);
return sysUser.getUserId();
}
评论 (0)