鉴于
我正在使用Spring的@EnableJpaAuditing向我的实体添加审核信息。我的JPA审核配置如下所示:
@Configuration
@EnableJpaAuditing
@Slf4j
public class JpaAuditingConfiguration {
@Bean
public AuditorAware<String> auditorAware() {
return
() -> {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
// there must always be an authentication context
// return null here, which will later cause a constraint violation exception when trying to store into
// the DB
return null;
} else {
final String userName = authentication.getName();
log.trace("Found Auditor: {}", userName);
return userName;
}
};
}
}
我的实体看起来像这样:
@Entity
@Table(schema = "mfe", name = "my_first_entity")
@ToString(exclude = {"mySecondEntities"})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@EntityListeners({ BusinessKeyEntityListener.class })
public class MyFirstEntity extends AbstractModifiable {
// here are some properties
@OneToMany(mappedBy = "myFirstEntity", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<MySecondEntity> mySecondEnttities;
}
AbstractModifiable超类看起来像这样:
@MappedSuperclass
@Getter
@Setter
@EntityListeners({ AuditingEntityListener.class })
public abstract class AbstractModifiable {
@Version
private Integer version;
@CreatedDate
private Instant created;
@CreatedBy
private String createdBy;
@LastModifiedDate
private Instant lastModified;
@LastModifiedBy
private String lastModifiedBy;
}
第一个实体的表名是:
MFE。的 my_first_entity
第二个实体的表名是:
MSE。的 my_second_entity
1)
时使用entityManager来保存和更新我的实体my_first_entity:
myFirstEntityRepository.save(myFirstEntity);
然后审核以预期的方式发生,我的数据库中my_first_entity表的属性如“last_modified”更改。
2)
时使用手动脚本更新未使用entityManager的表my_first_entity。
然后没有像“last_modified”这样的审核信息被添加到表my_first_entity中。
3)
时使用手动脚本更新未使用entityManager的表my_first_entity。
之后我使用JPA entityManager来持久化另一个实体:
@Transactional
public void createSnapshotEvents(String eventType, String flowId) {
Stream snapshotItemsStream = this.tarbelaSnapshotProvider.getSnapshot(eventType);
Iterators.partition(snapshotItemsStream.iterator(), this.tarbelaProperties.getSnapshotBatchSize().intValue()).forEachRemaining((batch) -> {
List events = (List)batch.stream().map((item) -> {
return this.eventLogMapper.createEventLog(EventDataOperation.SNAPSHOT, item, flowId);
}).collect(Collectors.toList());
this.eventLogRepository.save(events);
});
this.eventLogRepository.flush();
}
然后在表my_first_entity中添加了审核信息,这是我不期望的。
我希望我的实体my_first_entity没有被触及,如果我对我的表进行手动修改,审核就不会发生。