实体类:
在类上加上注解@EntityListeners(AuditingEntityListener.class)
相关属性上使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy注解
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public abstract class BaseEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@TableId
@ApiModelProperty(value = "唯一标识")
private String id = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
@ApiModelProperty(value = "创建者")
@CreatedBy
private String createBy;
@CreatedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新者")
@LastModifiedBy
private String updateBy;
@LastModifiedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "删除标志 默认0")
private Integer delFlag = CommonConstant.STATUS_NORMAL;
}
启动类:
启动类使用@EnableJpaAuditing启用JPA审计,此时时间字段已经可以赋值。
// 启用JPA审计
@EnableJpaAuditing
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}
实现AuditorAware
接口:
自定义配置类实现AuditorAware
接口,重写getCurrentAuditor方法,给CreatedBy和LastModifiedBy赋值。本代码使用的是Security安全框架,所以通过Security即可获取用户名。
@Configuration
public class UserAuditor implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
UserDetails user;
try {
user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.ofNullable(user.getUsername());
}catch (Exception e){
return Optional.empty();
}
}
}