【发布时间】: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