【问题标题】:Spring Boot Auditing - map current user to @CreatedBy, @LastModifiedBySpring Boot 审计 - 将当前用户映射到 @CreatedBy、@LastModifiedBy
【发布时间】:2021-03-06 15:57:56
【问题描述】:

所以我有一个使用 @MappedSuperClass 的审计类,它会更新 createdBy 和 updatedBy 的值,但它不会在 User 实体上添加外键,因此没有数据库验证

这是审计类


@Getter
@Setter
@MappedSuperclass
@JsonIgnoreProperties(
        value = {"createdBy", "updatedBy"},
        allowGetters = true
)
public abstract class UserDateAudit extends DateAudit {

    @CreatedBy
    @Column(name = "created_by", nullable = false, updatable = false)
    public Long createdBy;

    @LastModifiedBy
    @Column(name = "updated_by", nullable = false)
    public Long updatedBy;
}

我搜索了如何使用@Inheritance 执行此操作,但没有完全理解。 那么如何实现这个类与User实体的连接呢?

编辑 1 这是我实现的审计配置。

@Configuration
@EnableJpaAuditing
public class AuditingConfig {

    @Bean
    public AuditorAware<Long> auditorProvider() {
        return new SpringSecurityAuditAwareImpl();
    }

}

class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {

    @Override
    public Optional<Long> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null ||
                !authentication.isAuthenticated() ||
                authentication instanceof AnonymousAuthenticationToken) {
            return Optional.empty();
        }

        UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

        return Optional.ofNullable(userPrincipal.getId());
    }
}

编辑 2 明确我的意思 所以如何使用@MappedSuperclass 以外的东西来实现这个“我希望能够在继承 UserDateAudit 的所有表中映射用户引用,以便它是所有这些表的外键(这将添加一个验证用户 ID 实际存在)不仅仅是一个常规列”。

【问题讨论】:

  • 您需要实现org.springframework.data.domain.AuditorAware接口,并在getCurrentAuditor方法中添加获取当前登录用户的逻辑。示例见github.com/gtiwari333/spring-boot-blog-app/blob/master/src/main/…
  • @OmarAbdelhady @MappedSuperclass 继承模型未在数据库级别进行镜像,UserDateAudit 类的 hance 字段可以属于不同的表,具体取决于扩展它的目标实体。所以,你的问题不清楚。
  • 我知道@MappedSuperclass 没有被镜像,所以如何使用其他东西来实现这个“使用什么来能够在继承 UserDateAudit 的所有表中映射用户引用,以便它是所有这些表的外键(这将添加用户 ID 实际存在的验证)而不仅仅是常规列。

标签: java spring spring-boot hibernate jpa


【解决方案1】:

您需要实现org.springframework.data.domain.AuditorAware接口,并在getCurrentAuditor方法中添加检索当前登录用户的逻辑。

@Component
@RequiredArgsConstructor
public class AuditorResolver implements AuditorAware<YOUR_TYPE> {
 
    @Override
    public Optional<YOUR_TYPE> getCurrentAuditor() {

        //code to retrieve the currently logged in user and return the id/user object 
    }
}

查看示例:https://github.com/gtiwari333/spring-boot-blog-app/blob/master/src/main/java/gt/app/config/AuditorResolver.java

文档也描述得很漂亮:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing.basics

【讨论】:

  • 是的,这就是我所做的,我会将其包含在问题中。 ,但我的问题是,在执行此操作时,如何将 createdBy 和 updatedBy 值映射到 User 表,以使休眠添加引用该 SuperClass 的每个子类型(实体)上的用户表的外键
  • 我做到了,这就是我要找的,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2016-03-03
  • 2021-09-03
  • 1970-01-01
  • 2020-02-24
  • 2016-06-27
  • 1970-01-01
相关资源
最近更新 更多