Spring MongoRepository is updating or upserting instead of inserting

后端 未结 2 1819
甜味超标
甜味超标 2021-02-02 09:24

I\'m using a :

org.springframework.data.mongodb.repository.MongoRepository

I start with an empty DB and create an object with _id = 1234<

相关标签:
2条回答
  • 2021-02-02 09:55

    Save, by definition, is supposed to update an object in the upsert style, update if present and insert if not. Read the save operation documentation on the MongoDb website

    The insert operation in mongodb has the behavior you expect, but from the MongoRepository documentation it appears that insert is delegated to save so it won't make any difference. But you can give that a try and see if it works for you. Otherwise you can just do a get before to check if the object exists, since it is an index lookup it will be fast.

    Edit: Check your repository version, insert was introduced in version 1.7.

    0 讨论(0)
  • 2021-02-02 09:59

    the application shall update only when you have @Id annotation for one of the field, after long difficulty had found this

    @Document(collection="bus")
    public class Bus {
    
    //  @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)
        @Id
        private String busTitle; 
        private int totalNoOfSeats;
        private int noOfSeatsAvailable; 
        private String busType; 
    }
    

    but somehow I could not use @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)

    0 讨论(0)
提交回复
热议问题