vendredi 28 août 2015

Iterate through collection attribute of object with reflection

I'm trying to implement this solution in my code regarding cascading save in spring data mongodb. It works for normal class like this.

public class Test{

    @Id
    private String id;

    @DBRef
    @CascadeSave
    private Contact contact;
}

But I have something like this.

public class Test{

    @Id
    private String id;

    @DBRef
    @CascadeSave
    private Set<Contact> contacts = new HashSet<>();
}

I want to change the code in the listener which is in the link I have given to work with collections. I have tried several things and with no success. Apart from that, if there is another way accomplish this task, it would be appreciated, even though it is a separate question.

My listener code given below, which is not much difference to the example link.

public class CascadingMongoEventListener extends AbstractMongoEventListener {

private static final Logger logger = LoggerFactory.getLogger(CascadingMongoEventListener.class);

@Autowired
private MongoOperations mongoOperations;

@Override
public void onBeforeConvert(final Object source) {
     ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            try {
                if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
                    final Object fieldValue = field.get(source);
                    if (fieldValue != null) {

                        if (Collection.class.isAssignableFrom(field.getType())) {
                            @SuppressWarnings("unchecked")
                            Collection models = (Collection) fieldValue;
                            for (Object model : models) {
                               mongoOperations.save(model);
                            }
                        } else {
                            mongoOperations.save(fieldValue);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    });
}

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

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

    public boolean isIdFound() {
        return idFound;
    }
}
}





Aucun commentaire:

Enregistrer un commentaire