@CreatedBy @LastModifiedBy注释不起作用

时间:2020-01-28 16:49:02

标签: hibernate spring-boot jpa spring-data-jpa

每当我创建一个需要自动使用的用户时,该用户便已使用@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;
    }

2 个答案:

答案 0 :(得分:1)

在应用程序类中添加以下注释。

@EnableJpaAuditing(auditorAwareRef = "auditorAware")

定义bean:

@Bean
public AuditorAware<String> auditorAware(){
    return new CustomAuditAware();
}

创建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();
}

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

答案 1 :(得分:0)

您需要创建实现AuditorAware<?>的自定义类,才能定义哪个是当前的审核员。因此,让我们通过以下代码进行定义:

public class AuditingService implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        return Optional.of("Bhargav");
    }
}