springboot jpa使用@CreatedBy @LastModifiedBy自动保存创建者等信息

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值