在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.3、@EntityListeners(AuditingEntityListener.class):需要开启domain对象的监听,否则无法监测到对象的修改
BaseEntity.java
package com.imddy.layuiadmin.common;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "create_by", nullable = false, updatable = false)
@JsonIgnore
private String createBy;
@CreatedDate
@Column(name = "create_time", nullable = false, updatable = false)
@JsonIgnore
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
@LastModifiedBy
@Column(name = "update_by", nullable = false)
@JsonIgnore
private String updateBy;
@LastModifiedDate
@Column(name = "update_time", nullable = false)
@JsonIgnore
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime;
}
3、实现AuditorAware接口
ShiroAuditorAware.java
package com.imddy.layuiadmin.auditoraware;
import org.apache.shiro.SecurityUtils;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class ShiroAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
//返回会话中或者指定的用户名
//自己去处理获取用户名
//return Optional.of((String) SecurityUtils.getSubject().getPrincipal());
return Optional.of("用户名");
/** 用于审计的用户的名称 */
}
}
4、启用JPA Audit注解@EnableJpaAuditing(xxxApplication.java也就是项目的启动类中)
EnableJpaAuditingConfig.java
package com.imddy.layuiadmin.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@Configuration
@EnableJpaAuditing(auditorAwareRef="shiroAuditorAware")
public class EnableJpaAuditingConfig {
}
//1、这种是全部开启
//@EnableJpaAuditing
//2、这种是指定开启
//@EnableJpaAuditing(auditorAwareRef="shiroAuditorAware")