繁体   English   中英

在Spring Data(MongoDB)中实现findOne

[英]Implementing findOne in Spring Data (MongoDB)

我在执行MongoOperations类的findOne方法时遇到一些问题,目前此方法返回null。 我在mongoDB中的数据结构如下所示:

> db.news.find({_id:1})
{ "_id" : 1, "title" : "first title", "text" : "first text" }
> db.news.find({_id:{$type:1}})
{ "_id" : 1, "title" : "first title", "text" : "first text" }

如您所见,_id字段具有Double类型。 我的Java类看起来像这样:

@Repository
public class NewsService {

    @Autowired
    private MongoOperations mongoOperations;

    public static final String COLLECTION_NAME = "news";

    //this method executes ok
    public List<NewsEntity> getAllNews() {
        return mongoOperations.findAll(NewsEntity.class, COLLECTION_NAME);
    }

    //but this method return null     
    public NewsEntity getNewsDetail(Long id) {
        return mongoOperations.findOne(Query.query(Criteria.where("_id").is(id)), NewsEntity.class);
    }

实体类:

@Document
public class NewsEntity {

 @Id
 private Long id;
 private String title;
 private String text;


 public Long getId() {
     return id;
 }

 public void setId(Long id) {
     this.id = id;
 }

 public String getTitle() {
     return title;
 }

 public void setTitle(String title) {
     this.title = title;
 }

 public String getText() {
     return text;
 }

 public void setText(String text) {
     this.text = text;
 } 
}

和Spring控制器:

@Controller
public class MainController {
 @Autowired
 private NewsService newsService;

 @RequestMapping(value="/news/details/{newsId}",method = RequestMethod.GET)
 public String getNewsDetails(ModelMap model, @PathVariable("newsId") Long newsId) {
     //newsEnt is null here...
     NewsEntity newsEnt = newsService.getNewsDetail(newsId);

     model.addAttribute("newsDet", newsEnt);
     return "newsdetails";
 }
}

您正在直接调用mongoOperations实例,而不是首先检索集合。 就像您实现的findAll方法一样,您还需要包含该集合作为参数的表单:

public NewsEntity getNewsDetail(Long id) {
    return mongoOperations.findOne(
        Query.query(Criteria.where("_id").is(id)),
        NewsEntity.class,
        COLLECTION_NAME
    );
}

findOne的文档中对此进行了介绍,另请参见摘要中可用的方法签名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM