如何在 JPA 审计中强制 @CreatedBy 的值

问题描述

我正在运行一个带有 JPA 的 spring boot 项目(spring-data-jpa 版本 2.3.0 / hibernate 5.1.0) 如何强制使用@CreatedBy 注释的@Entity 字段的值?

实体:

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;

@Entity(...)
@Getter
@Setter
@EntityListeners(AuditingEntityListener.class)
public class SomeEntity{

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_timestamp",nullable = false,updatable = false)
    @CreatedDate
    private Date createTimestamp;

    @Column(name = "create_user")
    @CreatedBy
    private String createuser;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "update_timestamp")
    @LastModifiedDate
    private Date updateTimestamp;

    @Column(name = "update_user")
    @LastModifiedBy
    private String updateUser;
}

配置:

@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
@Component
public class AuditConfig implements AuditorAware<String> {

    /**
     * The Constant SYstem_ACCOUNT.
     */
    public static final String SYstem_ACCOUNT = "system";

    /**
     * Gets the current auditor.
     *
     * @return the current auditor
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        String currentUser = getUserFromSecurityContext();
        return Optional.ofNullable(currentUser);
    }
}

问题是即使我用这个代码强制值:

someEntity.setcreateuser("some other user"); 

该值会被 JPA 自动覆盖。 除了在表/实体中创建另一个字段之外,还有其他解决方案吗?

解决方法

定义您自己的 CustomCreatedBy 注释。使用 Entity lifecycle @PrePersist 您将获得所有具有自定义注释的字段,如果它们为空,则设置指示当前用户的值;如果不是,则保留现有值。