@CreatedBy @LastModifiedBy 注释不起作用

Bha*_*tha 4 hibernate jpa spring-data-jpa spring-boot

当我创建一个需要自动获取的任何用户时,该用户使用 @CreatedBy 注释创建了该用户,并且当我操作任何需要使用 @LastModifiedBy 注释自动获取的内容时。但这现在行不通了。可能是什么原因?

This is my entity class

@Slf4j
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @CreatedBy
    @Column(name = "created_by" , nullable = false, length = 50, updatable = false) 
    @JsonIgnore
    private String createdBy;
    @CreatedDate
    @Column(name = "created_date", updatable = false)
    @JsonIgnore
    private Instant createdDate = Instant.now();
    @LastModifiedBy
    @Column(name = "last_modified_by", length = 50)
    @JsonIgnore
    private String lastModifiedBy;
    @LastModifiedDate
    @Column(name = "last_modified_date")
    @JsonIgnore
    private Instant lastModifiedDate = Instant.now();
    @Transient
    public <T> T getView(Class<T> viewClass) {
        try {
            T view = viewClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(this, view);
            return view;
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            log.error("Error mapping model to view", e);
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

Man*_*oor 10

将以下注释添加到您的应用程序类中。

@EnableJpaAuditing(auditorAwareRef = "auditorAware")
Run Code Online (Sandbox Code Playgroud)

定义bean:

@Bean
public AuditorAware<String> auditorAware(){
    return new CustomAuditAware();
}
Run Code Online (Sandbox Code Playgroud)

创建 CustomAuditAware 类:

public class CustomAuditAware implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !authentication.isAuthenticated()) {
        return null;
    }

    return ((User) authentication.getPrincipal()).getUsername();
}
Run Code Online (Sandbox Code Playgroud)

https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-auditing-part-two/