我想做一个功能,可以自动监控和更新createdBy、modifiedBy、createdAt、modifiedAt。我决定选择使用 JPA AuditingEntityListener。但是,在某些情况下,我想手动设置createdBy和modifiedBy,但它不起作用。我该怎么办?
实体:
@Data
@SuperBuilder
@EntityListeners({AuditingEntityListener.class})
public abstract class BaseEntity {
@CreatedDate
@Column(nullable = false, updatable = true)
private LocalDateTime createdDate;
@LastModifiedDate
@Column(nullable = false)
private LocalDateTime modifiedDate;
@CreatedBy
@Column(nullable = false, updatable = true)
private Integer createdBy;
@LastModifiedBy
@Column(nullable = false)
private Integer modifiedBy;
@Column(nullable = false)
private Boolean deleteFlag = false;
}
AuditAwareConfig:
@Component
public class ApplicationAuditAware implements AuditorAware<Integer>{
@Override
public Optional<Integer> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) {
return Optional.of(0);
}
User user = (User) authentication.getPrincipal();
return Optional.of(user.getId());
}
}
我想使用
entity.setCreatedBy('John')
而不是使用 AuditingEntityListener.class。
您可以尝试以下策略