您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在将请求添加到MongoDB之前如何处理Spring Data中的插入请求?

在将请求添加到MongoDB之前如何处理Spring Data中的插入请求?

感觉最好还是编写一个自定义控制器,而不是在这里使用Spring Data REST,因为您基本上需要两种资源:一种用于添加链接或返回现有资源,另一种用于通过哈希来检索原始URI。

在第一种方法中,您只需要调用存储库方法findByLongURL(…)并使用获得的URL实例(如果您有结果),或采取第二步来实际创建哈希并保存URL实例思想存储库。第二个资源基本上只是调用您已经存在的方法

这很简单,也很容易消化。

如果您需要将前一种方法的实现作为原子操作,则需要手动实现存储库查询方法(有关阅读参考文档中相关部分的一般说明):

class UrlRepositoryImpl implements UrlRepositoryCustom {

  private final MongoOperations operations;

  public UrlRepositoryImpl(MongoOperations operations) {
    this.operations = operations;
  }

  @Override
  public URL findOrInsert(String source) {

    // What to find?
    Query query = Query.query(Criteria.where("longURL").is(source);

    // What to write if nothing can be found
    Update update = new Update()
      .setOnInsert("longURL", source)
      .setOnInsert("hash", calculatedHash);

    FindAndModifyOptions options = new FindAndModifyOptions.options()
      .returnNew(true) // returns the document insert (if so)
      .upsert(true); // insert document if it doesn't exist

    return operations.findAndModify(query, update, options, URL.class);
  }
}

如您所见,这涉及处理一些较低级别的细节(尽管可以通过使用静态导入来减少冗长程度),但基本上可以为您提供原子操作。

mongodb 2022/1/1 18:18:38 有526人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶