我是Spring Data Mongo的新手.我有一个场景,我想创建一个研究,如果已经不存在于mongo db中.如果它已经存在,那么我将使用新值更新它.
我尝试了以下方式,在我的情况下工作正常,但就性能而言,我不确定这是更正等的正确/最佳/建议方式.
有人可以指导一下吗?
public void saveStudy(List<Study> studies) {
        for (Study study : studies) {
            String id = study.getId();
            Study presentInDBStudy = studyRepository.findOne(id);
            //find the document, modify and update it with save() method.
            if(presentInDBStudy != null) {
                presentInDBStudy.setTitle(task.getTitle());
                presentInDBStudy.setDescription(study.getDescription());    
                presentInDBStudy.setStart(study.getStart());
                presentInDBStudy.setEnd(study.getEnd());
                repository.save(presentInDBStudy);
            }
            else
                repository.save(study);
        }
    }
您将必须使用MongoTemplate.upsert()来实现此目的。您将需要添加两个以上的类:StudyRepositoryCustom这是一个interface扩展此接口的类,例如StudyRepositoryImpl
interface StudyRepositoryCustom {
   public WriteResult updateStudy(Study study);
}
将您的当前更新StudyRepository为此extendinterface
@Repository
public interface StudyRepository extends MongoRepository<Study, String>, StudyRepositoryCustom {
   // ... Your code as before
}
并添加一个实现StudyRepositoryCustom. 这是我们将提供@Autowire的MongoTemplate实现,用于更新Study或保存它(如果它不存在)。我们使用该MongoTemplate.upsert()方法。
class StudyRepositoryImpl implements StudyRepositoryCustom {
   @Autowired
   MongoTemplate mongoTemplate;
   public WriteResult updateStudy(Study study) {
      Query searchQuery = new Query(Criteria.where("id").is(study.getId());
      WriteResult update = mongoTemplate.upsert(searchQuery, Update.update("title", study.getTitle).set("description", study.getDescription()).set(...)), Study.class);
      return update;
   }
}
请注意,StudyRepositoryImplSpring Data 基础设施将自动选取它,因为我们遵循了扩展核心存储库接口名称的命名约定:Impl
检查github 上的此示例,了解@Autowire-ing aMongoTemplate并使用如上所述的自定义存储库。
我还没有测试过代码,但它会指导你:-)
| 归档时间: | 
 | 
| 查看次数: | 539 次 | 
| 最近记录: |