JPA使用审计功能新增时, 不自动更新@LastModifiedDate和@LastModifiedBy字段

JPA使用审计功能新增时, 不自动更新@LastModifiedDate和@LastModifiedBy字段

  • 疑问
  • 查询源码
  • 解决方案

疑问

JPA使用审计功能, 网上有一大堆demo. 但是使用时, 会发现创建的时候会自动填写 LastModifiedDate
LastModifiedBy字段, 我这边需求是创建时保持update相关字段为null

查询源码

查看org.springframework.data.auditing.AuditingHandler

/**
 * Sets modifying and creating auditor. Creating auditor is only set on new auditables.
 * 
 * @param auditable
 * @return
 */
private Optional<Object> touchAuditor(AuditableBeanWrapper<?> wrapper, boolean isNew) {

	Assert.notNull(wrapper, "AuditableBeanWrapper must not be null!");

	return auditorAware.map(it -> {

		Optional<?> auditor = it.getCurrentAuditor();

		Assert.notNull(auditor,
				() -> String.format("Auditor must not be null! Returned by: %s!", AopUtils.getTargetClass(it)));

		auditor.filter(__ -> isNew).ifPresent(foo -> wrapper.setCreatedBy(foo));
		auditor.filter(__ -> !isNew || modifyOnCreation).ifPresent(foo -> wrapper.setLastModifiedBy(foo));

		return auditor;
	});
}

/**
 * Touches the auditable regarding modification and creation date. Creation date is only set on new auditables.
 *
 * @param wrapper
 * @return
 */
private Optional<TemporalAccessor> touchDate(AuditableBeanWrapper<?> wrapper, boolean isNew) {

	Assert.notNull(wrapper, "AuditableBeanWrapper must not be null!");

	Optional<TemporalAccessor> now = dateTimeProvider.getNow();

	Assert.notNull(now, () -> String.format("Now must not be null! Returned by: %s!", dateTimeProvider.getClass()));

	now.filter(__ -> isNew).ifPresent(it -> wrapper.setCreatedDate(it));
	now.filter(__ -> !isNew || modifyOnCreation).ifPresent(it -> wrapper.setLastModifiedDate(it));

	return now;
}

可以看到其中主要是auditor.filter(__ -> !isNew || modifyOnCreation)里面的modifyOnCreation导致创建时也会更新 update 相关字段

解决方案

调用AuditingHandler.setModifyOnCreation(false);即可, 例如在审计类中, 加入

public class AuditorConfig implements AuditorAware<String> {
	AuditingHandler auditingHandler;

    public AuditorConfig(AuditingHandler auditingHandler) {
       auditingHandler.setModifyOnCreation(false);
       this.auditingHandler = auditingHandler;
    }
   
    @Override
    public Optional<String> getCurrentAuditor() {
        ...
        return Optional.of("System");
    }
}

如果有其他方法更新这个modifyOnCreation, 欢迎在评论区给出更优化的答案

你可能感兴趣的:(spring,jpa,java,jpa)