【发布时间】:2020-01-17 07:20:33
【问题描述】:
我想在数据库中实现对谁以及何时创建/更新实体的引用。 createdAt 和 updatedAt 日期已经生效。
但是我可以看到,当我设置断点时,getCurrentAuditor 方法的返回被调用了大约十次,直到响应到达客户端。并且响应是 CONFLICT HttpStatus-Code 的错误。
我有一个名为 BaseEntity 的类,其中定义了属性。
在下面查看我的课程:
class AuditorAwareImpl implements AuditorAware<Person> {
@Autowired
private PersonRepository personRepo;
@Override
public Optional<Person> getCurrentAuditor() {
return Optional.of(personRepo.findByUserPrincipalName(SecurityContextHolder.getContext().getAuthentication().getName() + "@email.com"));
}
}
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
class JpaConfig {
@Bean
public AuditorAware<Person> auditorProvider() {
return new AuditorAwareImpl();
}
}
@Data
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
protected Long id;
@CreatedDate
private Date createdAt;
@CreatedBy
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(referencedColumnName="id")
private Person createdBy;
@LastModifiedDate
private Date updatedAt;
@LastModifiedBy
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(referencedColumnName="id")
private Person updatedBy;
@PrePersist
protected void prePersist() {
if (this.createdAt == null) createdAt = new Date();
if (this.updatedAt == null) updatedAt = new Date();
}
@PreUpdate
protected void preUpdate() {
this.updatedAt = new Date();
}
@PreRemove
protected void preRemove() {
this.updatedAt = new Date();
}
}
从 Zorglube 编辑 v1(对我不起作用)
class AuditorAwareImpl implements AuditorAware<Person> {
@Autowired
private ApplicationContext context;
@Override
public Optional<Person> getCurrentAuditor() {
PersonRepository personRepo = context.getBean(PersonRepository.class);
return Optional.of(personRepo.findByUserPrincipalName(SecurityContextHolder.getContext().getAuthentication().getName() + "@email.com"));
}
}
【问题讨论】:
标签: java spring spring-boot spring-security spring-data-jpa