springboot 中用注解生成审计(Auditing)字段。如:@LastModifiedBy

在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy。维护数据库的建立时间、建立人、最后修改时间、最后修改人。实现步骤以下:spring

1、在须要的实体上作下面的改造。

  • 在实体类上使用注解。@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

2、增长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());
    }
}

3、在springbooot入口类上配置@EnableJpaAuditing。

@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class TestApplication {
}

其中的auditorAwareRef = "auditorAware"就是上面配置的@Component("auditorAware")数据库

相关文章
相关标签/搜索