gpt4 book ai didi

java - OnBeforeSave 被调用但没有任何反应

转载 作者:行者123 更新时间:2023-12-05 08:54:31 26 4
gpt4 key购买 nike

我正在尝试检查我要保留的对象是否已经有一个“所有者”,如果没有,我将设置登录用户。此 EventListener 适用于 Contact 的任何其他字段,并且在我调试时它确实设置了用户。 MongoRepository 保存方法的返回值包含正确的设置用户,但当我查看数据库时,用户未保存。

OwnedByUserMongoEventListener 类

public void onBeforeSave(BeforeSaveEvent<Contact> event) {
Contact source = event.getSource();
ReflectionUtils.doWithFields(source.getClass(), new OwnedByUserCallback(source));
}

OwnedByUserCallback 类

@Override
public void doWith(java.lang.reflect.Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
final Object fieldValue = field.get(getSource());
if (field.isAnnotationPresent(OwnedByUser.class)) {
if ( fieldValue == null ) {
JwtUser principal = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = mongoOperations.findOne(Query.query(Criteria.where("username").is(principal.getUsername())), User.class);
field.set(getSource(), user);
}
}

}

/

Contact extends Auditable {

@Id
private String id;

@Indexed(unique=true,sparse=true)
@NotNull
private Long seqId;

private BasicDBObject attributes = new BasicDBObject(new HashMap<>());

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@SuppressWarnings("unchecked")
public Map<String, Object> getAttributes() {
return attributes.toMap();
}

public void setAttributes(Map<String, Object> attributes) {
this.attributes = new BasicDBObject(attributes);
}

public String toString() {
return "ID: "+getId() +" Attributes: " + getAttributes();
}

public Long getSeqId() {
return seqId;
}

public void setSeqId(Long seqId) {
this.seqId = seqId;
}

}



public abstract class Auditable {

@CreatedDate
private Date createdDate;

@DBRef
@CreatedBy
private User createdBy;

@DBRef
@OwnedByUser
private User owner;

@LastModifiedDate
private Date updatedDate;

@DBRef
@LastModifiedBy
private User updatedBy;

public Date getCreatedDate() {
return createdDate;
}

public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}

public User getCreatedBy() {
return createdBy;
}

public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}

public Date getUpdatedDate() {
return updatedDate;
}

public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}

public User getUpdatedBy() {
return updatedBy;
}

public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}

public User getOwner() {
return owner;
}

public void setOwner(User owner) {
this.owner = owner;
}

}

最佳答案

我正在尝试使用 OnBeforeSave,但在调用 MongoConverter 后无法更改属性,除非更改 event.getDBObject()。如果您想使用您的类 Object 进行更改,那么您需要使用 OnBeforeConvert ...由于文档不完善,我花了很多时间来跟踪它...

关于java - OnBeforeSave 被调用但没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49536371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com