【问题标题】:Java Spring 5 Get and findById mongo MonoOnErrorResumeJava Spring 5 Get 和 findById mongo MonoOnErrorResume
【发布时间】:2019-12-16 21:22:27
【问题描述】:

这里是春季新手,尝试通过 findById(id, Object) 在 mongo db 中进行 GET http 查询。

但它似乎不起作用。我可以 POSTPUT 但是当通过 ID 调用查询时我得到这个错误 MonoOnErrorResume强>

  • 我正在使用 EmbeddedMongoDB

控制器

public class ContentController {
    public static final String CONTENT_V_1_CONT = "/contents/v1/cont/";

    private final ContentService contentService;

    @Autowired
    public ContentController(ContentService contentService) {
        this.contentService = contentService;
    }

    @GetMapping(path = "{id}", produces = 
    MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Mono<Content> getContent(@PathVariable String id) {
       System.out.println(contentService.getContent(id)); // 
       MonoOnErrorResume
     return contentService.getContent(id);
    }

    @PostMapping(path = "", produces = 
    MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = 
    MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Mono<Content> createContent(@RequestBody Mono<Content> content){
       return  contentService.createContent(content);
     }

服务实施

public final ReactiveMongoOperations reactiveMongoOperations;

@Autowired
public ContentServiceImplementation(ReactiveMongoOperations reactiveMongoOperations) {
   this.reactiveMongoOperations = reactiveMongoOperations;
}

@Override
public Mono<Content> getContent(String id) {
   return reactiveMongoOperations.findById(id, Content.class);
}

@Override
public Mono<Content> createContent(Mono<Content> contentMono) {
   return reactiveMongoOperations.save(contentMono);
}

数据配置不知道有没有用

@Bean
public ReactiveMongoDatabaseFactory mongoDatabaseFactory(MongoClient mongoClient){
   return new SimpleReactiveMongoDatabaseFactory(mongoClient, DATABASE_NAME);
}

@Bean
public ReactiveMongoOperations reactiveMongoTemplate(ReactiveMongoDatabaseFactory mongoDatabaseFactory){
   return new ReactiveMongoTemplate(mongoDatabaseFactory);
}

如果我遗漏了一些关键信息,Lmk

【问题讨论】:

  • 发现我的错误,在模型中,getId getter方法输入错误。
  • 当我将其切换为 id 时,我的 id 就像 @Id private String content_id 一样

标签: java spring mongodb spring-boot spring-webflux


【解决方案1】:

你的问题可能来自你的控制器,你这样声明你的路径:

@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

因此,除非您在控制器类映射的末尾有 /,否则您将遇到问题,因为您的最终 URL 将如下所示:

http://localhost:8080/my/route/get1

而不是:

http://localhost:8080/my/route/get/1

您的@PathVariable 看起来也很奇怪,请尝试这样做:

@PathVariable("id") String id

为了确保 Spring 将 {id} 映射到您的 @PathVariable

【讨论】:

  • 我尝试更改路径变量但仍然一无所获,我得到的响应状态为 200 但响应对象仍然为空。我还更新了上面的代码,这样你就可以看到路由路径,我确实按照你写的那样设置了路径。
猜你喜欢
  • 2019-03-14
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
相关资源
最近更新 更多