gpt4 book ai didi

java - spring data 和 mongodb 中级联保存

转载 作者:行者123 更新时间:2023-12-02 00:53:20 25 4
gpt4 key购买 nike

我正在实现一个基于 spring data 和 mongodb 的应用程序。

@Document
public class User {

@Id
private ObjectId id;

private String name;

private Integer age;

@DBRef
private Address address;

@DBRef
@CascadeSave
private Set<Action> actions = new HashSet<Action>();

我需要将操作列表作为嵌入文档保存到用户中,为此我实现了自定义级联保存

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CascadeSave {
}

CascadingMongoEventListener.java

public class CascadingMongoEventListener extends AbstractMongoEventListener<Object> {

@Autowired
private MongoOperations mongoOperations;

@Override
public void onBeforeConvert(final BeforeConvertEvent<Object> event) {
final Object source = event.getSource();
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);

if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
final Object fieldValue = field.get(source);

if (fieldValue instanceof List<?>) {
for (Object item : (List<?>) fieldValue) {
checkNSave(item);
}
} else {
checkNSave(fieldValue);
}
}
}
});
}

private void checkNSave(Object fieldValue) {
DbRefFieldCallback callback = new DbRefFieldCallback();
ReflectionUtils.doWithFields(fieldValue.getClass(), callback);
if (!callback.isIdFound()) {
throw new MappingException("Oops, something went wrong. Child doesn't have @Id?");
}
mongoOperations.save(fieldValue);
}

private static class DbRefFieldCallback implements ReflectionUtils.FieldCallback {
private boolean idFound;

@Override
public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
if (field.isAnnotationPresent(Id.class)) {
idFound = true;
}
}
public boolean isIdFound() {
return idFound;
}
}
}

我尝试用操作列表保存用户

Action action = new Action();
action.setDescription("des");
action.setTime(ZonedDateTime.now());
User personHektor = new User();
personHektor.setName("Hektor");
personHektor.setActions(Stream.of(action).collect(Collectors.toSet()));
personRepo.save(personHektor);

但我有这个错误

org.springframework.data.mapping.MappingException: Oops, something went wrong. Child doesn't have @Id?

我将项目插入github以获得更多可见性

最佳答案

CascadingMongoEventListener 根据 List 检查 fieldValue,尽管它实际上是一个 Set
更改它(可能更改为 Collection),MappingException 将消失。
要另外解决 ZonedDateTime 问题,请注册一个 Converter 进行转换。

关于java - spring data 和 mongodb 中级联保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841095/

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