Spring Data审计功能@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy的使用

在Spring JPA中,在实体bean的属性上加注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,可以再实体插入数据库时进行设置值,这样以来,在对普通实体类的添加、修改操作时,就不用关心创建时间、更新时间这些信息了。本文以SpringBoot为例

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2、实体bean

注意:

2.1、@MappedSuperclass需要添加,因为一般这种domain类都是需要被继承的,为了在子类对象中能取到父类对象的属性,所以必须得加上;

2.2、@Audited:开启domain对象的审计功能

2.3、@EntityListeners(AuditingEntityListener.class):需要开启domain对象的监听,否则无法监测到对象的修改

@MappedSuperclass
@Audited
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @CreatedBy
    @Column(name = "created_by", nullable = false, length = 32, updatable = false)
    @JsonIgnore
    private String createdBy;

    @CreatedDate
    @Column(name = "created_date", nullable = false)
    @JsonIgnore
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private ZonedDateTime createdDate = ZonedDateTime.now();

    @LastModifiedBy
    @Column(name = "modified_by", nullable = false, length = 32)
    @JsonIgnore
    private String modifiedBy;

    @LastModifiedDate
    @Column(name = "modified_date")
    @JsonIgnore
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private ZonedDateTime modifiedDate = ZonedDateTime.now();

    // 省略对应的 set/get 方法......
}

3、实现AuditorAware接口

@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {
        //返回会话中或者指定的用户名
        //自己去处理获取用户名.
        return SecurityUtils.getCurrentUsername();
    }

}

4、启用JPA Audit注解@EnableJpaAuditing(xxxApplication.java也就是项目的启动类中)

@Slf4j
@SpringBootApplication
//1、这种是全部开启
//@EnableJpaAuditing
//2、这种是指定开启
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class ItmsApplication {

	public static void main(String[] args) {
		SpringApplication.run(ItmsApplication.class, args);
	}

}

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值