3

Say I have the following Collections

    public @Data  class Customer {

    @Id
    private String id;

    private String firstName;
    private String lastName;

    @DBRef
    private List<Address> addressList= new ArrayList<Address>();
}

and

public @Data class  Address {

    @Id
    private String id;
    private String address;
    private String type;
    private String customerID;
}

And each Customer has multiple addresses, and I have implemented MongoRepository. Saving customer for the First time is working pretty well customerRepo.save(customerObject) and before calling the save I am persisting multiple Address Objects and then setting those to the addressList. Next time when I am updating the same document and want to add a New set of Address to the existing list it is overwriting the whole addressList array. So basically what I have to do now to set new address like thisexistingCustomerObject.getAddressList().addAll(my new List of address) if there are thousand(or more than thousand) of elements or I am slicing the addressList array the following procedure won't be a good idea. My question is what is the best way to achieve this scenario? say if I don't want to use MongoTemplate. Is it possible Just using the MongoRepository

2
  • I don't think it is possible with just MongoRepositoy. You have to use mongotemplate and do a $pull Commented Apr 20, 2017 at 8:14
  • since I have added @DBRef to the child entries even usage of MongoRepositoy is not solving my problem because I want to prevent loading all of the child entries at a same time. Commented Apr 23, 2017 at 14:58

1 Answer 1

1

I don't think you can do it in that way. Previously i had the same situation, and I tried the following

1.org.springframework.core.convert.converter.Converter even I have managed to manipulate the DBObject but functions like $push or $set(wrapping them under key) does not work over there.

2.AbstractMongoEventListener by overriding onBeforeSave but Object manipulation was not taking place during save.

However you can try altering the mentioned

you can try override MongoRepository save method, It would better if someone point to the right direction. Otherwise for my scenario I had to create Custom repository(To update and delete document) which is working parallel with MongoRepository (for Insert and retrieve data/document), but I believe thats an ugly workaround. There has to be a cleaner way to do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.