在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
@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
private ZonedDateTime createdDate = ZonedDateTime.now();
@LastModifiedBy
@Column(name = "modified_by", nullable = false, length = 32)
@JsonIgnore
private String modifiedBy;
@LastModifiedDate
@Column(name = "modified_date")
@JsonIgnore
private ZonedDateTime modifiedDate = ZonedDateTime.now();
}
// 省略对应的 set/get 方法......
3、实现AuditorAware接口
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
//返回会话中或者指定的用户名
}
}
4、启用JPA Audit注解
@Configuration
@EntityScan
@EnableJpaRepositories
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
@Inject
private Environment env;
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
}