我有以下父类(super class)(摘要)
public abstract class AbstractAuditEntity {
@CreatedBy
private String createdBy;
}
我的数据库中有几个对象。现在我想要一个方法来克隆特定对象及其所有属性,包括createdBy。我可以将任何字符串设置为此值,但该值在保存到数据库之前会重置为当前经过身份验证的用户名。
如何防止 spring/jpa 覆盖已填充的 createBy 字段?
提前致谢!
最佳答案
不幸的是,这似乎是不可能的。
在 AuditingEntityListener 中,@PrePersist 方法如下所示:
@PrePersist
public void touchForCreate(Object target) {
Assert.notNull(target, "Entity must not be null!");
if (handler != null) {
AuditingHandler object = handler.getObject();
if (object != null) {
object.markCreated(target);
}
}
}
然后是 AuditingHandler:
public <T> T markCreated(T source) {
Assert.notNull(source, "Entity must not be null!");
return touch(source, true);
}
由于第二个参数为 true,因此它将始终设置createdBy 字段:
private Optional<Object> touchAuditor(AuditableBeanWrapper<?> wrapper, boolean isNew) {
Assert.notNull(wrapper, "AuditableBeanWrapper must not be null!");
return auditorAware.map(it -> {
Optional<?> auditor = it.getCurrentAuditor();
Assert.notNull(auditor,
() -> String.format("Auditor must not be null! Returned by: %s!", AopUtils.getTargetClass(it)));
auditor.filter(__ -> isNew).ifPresent(foo -> wrapper.setCreatedBy(foo));
auditor.filter(__ -> !isNew || modifyOnCreation).ifPresent(foo -> wrapper.setLastModifiedBy(foo));
return auditor;
});
}
但是,由于这似乎是一个有趣的功能,您应该继续并提出 future 的请求: https://jira.spring.io/projects/DATAJPA/issues/DATAJPA-1397?filter=allopenissues
关于java - 克隆JPA实体,包括用spring的createdBy注释的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839457/