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

用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);

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


遇见相同的问题,spring-data-mongodb版本是1.8.2.RELEASE.

在插入已有唯一索引id的数据时,没有返回值,也没有异常,也不会影响原本的数据。

后面我的解决版本是在插入之前先查询,如果根据id查询到已经存在数据,则不执行插入,将该条数据保存到返回结果。

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

如果你有更好的解决方案,欢迎交流。

【热门文章】
【热门文章】