Advertisement
Guest User

Untitled

a guest
Aug 28th, 2015
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. public class Test{
  2.  
  3. @Id
  4. private String id;
  5.  
  6. @DBRef
  7. @CascadeSave
  8. private Contact contact;
  9. }
  10.  
  11. public class Test{
  12.  
  13. @Id
  14. private String id;
  15.  
  16. @DBRef
  17. @CascadeSave
  18. private Set<Contact> contacts = new HashSet<>();
  19. }
  20.  
  21. public class CascadingMongoEventListener extends AbstractMongoEventListener {
  22.  
  23. private static final Logger logger = LoggerFactory.getLogger(CascadingMongoEventListener.class);
  24.  
  25. @Autowired
  26. private MongoOperations mongoOperations;
  27.  
  28. @Override
  29. public void onBeforeConvert(final Object source) {
  30. ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
  31.  
  32. public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
  33. ReflectionUtils.makeAccessible(field);
  34. try {
  35. if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
  36. final Object fieldValue = field.get(source);
  37. if (fieldValue != null) {
  38.  
  39. if (Collection.class.isAssignableFrom(field.getType())) {
  40. @SuppressWarnings("unchecked")
  41. Collection models = (Collection) fieldValue;
  42. for (Object model : models) {
  43. mongoOperations.save(model);
  44. }
  45. } else {
  46. mongoOperations.save(fieldValue);
  47. }
  48. }
  49. }
  50. } catch (Exception e) {
  51. logger.error(e.getMessage());
  52. e.printStackTrace();
  53. }
  54. }
  55. });
  56. }
  57.  
  58. private static class DbRefFieldCallback implements ReflectionUtils.FieldCallback {
  59. private boolean idFound;
  60.  
  61. public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
  62. ReflectionUtils.makeAccessible(field);
  63. if (field.isAnnotationPresent(Id.class)) {
  64. idFound = true;
  65. }
  66. }
  67.  
  68. public boolean isIdFound() {
  69. return idFound;
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement