Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test{
- @Id
- private String id;
- @DBRef
- @CascadeSave
- private Contact contact;
- }
- public class Test{
- @Id
- private String id;
- @DBRef
- @CascadeSave
- private Set<Contact> contacts = new HashSet<>();
- }
- 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;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement