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

}

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐