Spring Data JPA 审计功能

在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy。除了创建时间和修改时间,多了创建人和修改人两个字段。

审计功能步骤

实体类上加上注解@EntityListeners(AuditingEntityListener.class);
application启动类中加上注解@EnableJpaAuditing;
响应字段上加上@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy等注解;

注意:CreatedBy和LastModifiedBy的赋值需要实现AuditorAware接口来返回你需要插入的值。

编写AuditorAware

/**
 * 监听
 * @CreatedBy
 * @LastModifiedBy
 * 自动注入用户名
 */
@Configuration
public class UserAuditorAware implements AuditorAware<String> {
 
 
    @Override
    public Optional<String> getCurrentAuditor() {
        //TODO: 根据实际情况取真实用户
        return Optional.of("admin");
    }
}

在实体类中声明@EntityListeners和相应的注解

这里写一个BaseEntityModel。

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntityModel  implements Serializable {
 
    /**
     * 
     */
    private static final long serialVersionUID = -6163675075289529459L;
 
    @JsonIgnore
    String entityName = this.getClass().getSimpleName();
 
    @CreatedBy
    String createdBy;
 
    @LastModifiedBy
    String modifiedBy;
    /**
     * 实体创建时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    protected Date dateCreated = new Date();
 
    /**
     * 实体修改时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    protected Date dateModified = new Date();
 
     #省略getter setter
}

在Application 中启用审计@EnableJpaAuditing

@SpringBootApplication
@EnableJpaAuditing
public class Application {
    
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application .class, args);
    }
 
    /**
     * 测试中如果无法自动识别,可能是包路径的问题,采用手动声明bean的方式
     * @return
     */
    @Bean
    public UserAuditorAware setUserAuditorAware(){
        return new UserAuditorAware();
    }
}

原文链接:https://blog.youkuaiyun.com/weixin_34024034/article/details/89662485

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值