Announcement Announcement Module
No announcement yet.
CrudRepository and MongoDB - saving two equal objects / updating object Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • CrudRepository and MongoDB - saving two equal objects / updating object

    Does (with MongoDB) supports updating object that is already persisted via repository "save" method?

    First of all, if object had been already persisted, call to "save" method with equal object should do nothing (there should not be two equal objects stored in DB)

    Something like in the snippet below:
    CrudRepository<MyEntity> repo = (...)
    MyEntity entity = new MyEntity("key-123", "xxx");
    MyEntity entity2 = new MyEntity("key-123", "xxx"); // now we have two equal objects;; // nothing is done because this entity has been already persisted in DB

    Also, if object has changed, for example:

    Code: MyEntity("key-123", "yyy")
    Repository should find entity with key "key-123" and update it with value "xxx"->"yyy" instead of creating second document MyEntity("key-123", "yyy").

    From the tests, I've done it seems that CrudRepository #save method always persist object to db, even if equal object has been already persisted. So for example:
    for (int i=0; i<10; i++) { MyEntity("key-123", "xxx");
    would create 10 documents in Mongo database.
    But maybe I'm doing something wrong, or it is some way to prevent such behavior.

    (of course MyEntity has hasCode and equals methods overridden)

    Thanks in advance,
    Last edited by PiotrD; Oct 6th, 2011, 05:17 AM.

  • #2
    Ok, I've figured out that it works as I've expected, but only if I annotate one of class fields with @Id. Before, I allowed mongoDB to create identifiers and apparently, when comparing objects it takes into consideration only identifiers (if they are equal or not).