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);
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐