gpt4 book ai didi

java - 在 Spring Data (MongoDB) 中实现 findOne

转载 作者:行者123 更新时间:2023-11-29 03:21:01 25 4
gpt4 key购买 nike

我在执行 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 :

@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 的文档中对此进行了介绍, 另请参阅 summary 中可用的方法签名.

关于java - 在 Spring Data (MongoDB) 中实现 findOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23646983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com