1、创建一个实体类
在类和属性上标注对应的注解
@Data
@ApiIgnore
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
@CreatedBy
@ApiModelProperty(value = "创建人ID", hidden = true)
@Column(name = "create_by", updatable = false)
public Long createBy;
@CreatedDate
@ApiModelProperty(value = "创建时间", hidden = true)
@Column(name = "create_time", updatable = false)
public Date createTime;
@LastModifiedBy
@ApiModelProperty(value = "更新人ID", hidden = true)
@Column(name = "update_by",insertable = false)
public Long updateBy;
@LastModifiedDate
@ApiModelProperty(value = "更新时间", hidden = true)
@Column(name = "update_time",insertable = false)
public Date updateTime;
@ApiModelProperty(value = "是否删除(0未删除 1已删除)", hidden = true)
@Column(name = "del_flag",insertable = false)
public Integer delFlag;
@ApiModelProperty(value = "备注", hidden = true)
public String remark;
}
2、创建一个配置类去实现AuditorAware
@Slf4j
@Component
public class AuditorConfig implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Long userId = SecurityUtils.getUserId();
if (userId != null){
return Optional.of(userId);
} else {
return Optional.empty();
}
}
}
3、需要再启动类上配置@EnableJpaAuditing(auditorAwareRef = “auditorConfig”)注解
@SpringBootApplication
@EnableJpaAuditing(auditorAwareRef = "auditorConfig")
public class XlApplication {
public static void main(String[] args) {
SpringApplication.run(XlApplication.class, args);
}
}