首页 > 解决方案 > mongodb + spring:findById 不返回任何结果

问题描述

所以,我有一个带有引号格式的 mongodb 集合

{
  "_id":"5eb17aadb69dc744b4e70d2a",
  "quoteText":"Old age, believe me, is a good and pleasant thing. It is true you are gently shouldered off the stage, but then you are given such a comfortable front stall as spectator.",
  "quoteAuthor":"Confucius",
  "quoteGenre":"age",
  "__v":0
}

我正在尝试构建一个简单的 spring 应用程序,它将对该集合执行一些查询。

我的模型如下所示:

@Document("quotes")
public class Quote {

    @Id
    private String id;
    private String quoteAuthor;
    private String quoteText;
    private String quoteGenre;
    
    public Quote(String id, String quoteAuthor, String quoteText, String quoteGenre) {
        super();
        this.id = id;
        this.quoteAuthor = quoteAuthor;
        this.quoteText = quoteText;
        this.quoteGenre = quoteGenre;
    }

//getters and setters
    
}

我创建了一个 QuoteRepository 扩展 MongoRepository

public interface QuoteRepository extends MongoRepository<Quote, String> {

@Query("{ 'quoteAuthor' : ?0 }")
List<Quote> findByAuthor(String author);

}

和服务等级

@Service
public class QuoteService {

private final QuoteRepository repo;

public QuoteService(QuoteRepository repo) {
    this.repo = repo;
}

public Quote findById(String id) {
    return repo.findById(id)
            .orElseThrow(()->new RuntimeException("Can't find quote with id "+id));
}

public List<Quote> findByAuthor(String author) {
    return repo.findByAuthor(author);
}

public List<Quote> getAllQuotes() {
    return repo.findAll();
}

}

所以,我的 findByAuthor 方法和 findAll 一样工作正常,但是当我尝试 findById 时,我什么也没得到。我在这里想念什么?

谢谢你的帮助。

标签: springmongodb

解决方案


推荐阅读