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

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

    Does org.springframework.data.repository.CrudRepository (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:
    Code:
    CrudRepository<MyEntity> repo = (...)
    
    MyEntity entity = new MyEntity("key-123", "xxx");
    MyEntity entity2 = new MyEntity("key-123", "xxx"); // now we have two equal objects
    
    repo.save(entity);
    repo.save(entity2); // nothing is done because this entity has been already persisted in DB

    Also, if object has changed, for example:

    Code:
    repo.save(new 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:
    Code:
    for (int i=0; i<10; i++) {
      repository.save(new 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,
    Piotr
    Last edited by PiotrD; Oct 6th, 2011, 06: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).

    Comment

    Working...
    X