在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy。维护数据库的创建时间、创建人、最后修改时间、最后修改人。实现步骤如下: 一、在需要的实体上做下面的改造。- 在实体类上使用注解。@EntityListeners。
- 在响应的字段属性上加注解。如:@LastModifiedDate
- @MappedSuperclass
- @EntityListeners(AuditingEntityListener.class)
- public class BaseEntity {
- private static final long serialVersionUID = 7491626901163891174L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
- @JsonIgnore
- @Temporal(TemporalType.TIMESTAMP)
- @CreatedDate
- @Column(updatable = false)
- private Date createTime;
- @JsonIgnore
- @Temporal(TemporalType.TIMESTAMP)
- @LastModifiedDate
- @Column(updatable = false)
- private Date updateTime;
- @LastModifiedBy
- private String updatedBy;
- //省略getter、setter
复制代码 二、增加AuditorAware实现类。用于获取创建人、最后修改人。- @Component("auditorAware")
- public class AuditorAwareImpl implements AuditorAware<String> {
- @Override
- public Optional<String> getCurrentAuditor() {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- return Optional.of(authentication.getPrincipal().toString());
- }
- }
复制代码 三、在springbooot入口类上配置@EnableJpaAuditing。
- @SpringBootApplication
- @EnableCaching(proxyTargetClass = true)
- @EnableJpaAuditing(auditorAwareRef = "auditorAware")
- public class TestApplication {
- }
复制代码其中的auditorAwareRef = "auditorAware"就是上面配置的@Component("auditorAware")
|