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

在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")

转载于:https://my.oschina.net/kunBlog/blog/3011886

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值