简体   繁体   中英

cascade save in spring data and mongodb

I'm implementing an application based on spring data and 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>();

i need to save actions list as embedded document into the user, for that i implement custom cascade save

@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;
        }
    }
}

i try to save a user with a list of actions

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);

but i have this error

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

i pushed the project in github for more visibility

CascadingMongoEventListener checks the fieldValue against List though it's actually a Set .
Change that (to maybe Collection ) and the MappingException will go away.
To additionally solve the issue with ZonedDateTime please register a Converter for the conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM