search

Home  >  Q&A  >  body text

用spring-data-mongodb批量插入数据,如何知道有一部分数据没有插入成功?

我想用spring-data-mongodb的接口执行批量插入,每次插入100条数据。接口描述如下:

    /**
     * 参考:org.springframework.data.mongodb.core.MongoTemplate
     * 参考:org.springframework.data.mongodb.core.MongoOperations
     *
     * Insert a list of objects into the specified collection in a single batch write to the database.
     * 
     * @param batchToSave the list of objects to save.
     * @param collectionName name of the collection to store the object in
     */
    void insert(Collection<? extends Object> batchToSave, String collectionName);

然而这里存在一个问题:当有重复的唯一索引时,插入操作会“部分成功”——某些文档插入成功,某些插入失败。我想知道什么时候发生的插入失败,哪些失败了,哪些成功了。然而,上面的接口没有返回值。有谁碰到过这个问题吗?

大家讲道理大家讲道理2792 days ago595

reply all(1)I'll reply

  • 世界只因有你

    世界只因有你2017-05-02 09:19:54

    Encountered the same problem, spring-data-mongodb版本是1.8.2.RELEASE.

    When inserting data with a unique index id, there is no return value, no exception, and it will not affect the original data.

    My solution later is to query before inserting. If the data already exists based on the id query, the insertion will not be performed and the data will be saved to the returned result.

    public Person getObject(String id) {
            return mongoTemplate.findOne( new Query( Criteria.where( "id" ).is( id ) ),Person.class );
        }

    If you have a better solution, please share it.

    reply
    0
  • Cancelreply