Java 在Spring数据(MongoDB)中实现findOne
我在执行MongoOperations类的findOne方法时遇到一些问题,目前这个方法返回null。我在mongoDB中的数据结构如下所示:Java 在Spring数据(MongoDB)中实现findOne,java,mongodb,spring-mvc,spring-data-jpa,Java,Mongodb,Spring Mvc,Spring Data Jpa,我在执行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
> 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" }
@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);
}
正如您在上面所看到的,id字段具有双重类型。我的Java类如下所示:
> 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" }
@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);
}
和弹簧控制器:
@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
);
}
这在的文档中有介绍,另请参见中的可用方法签名。您直接调用
mongoOperations
实例,而不是首先检索集合。与您实现的findAll
方法类似,您还需要包含集合的表单作为参数:
public NewsEntity getNewsDetail(Long id) {
return mongoOperations.findOne(
Query.query(Criteria.where("_id").is(id)),
NewsEntity.class,
COLLECTION_NAME
);
}
这已在的文档中介绍,另请参阅中的可用方法签名。您的方法上未选择任何集合。由于您直接调用mongooperations而不检索集合,因此需要使用该方法签名类型。您的意思是我应该像这样向findOne方法添加新参数(collectionName):T findOne(查询查询,类entityClass,字符串collectionName)您的方法上没有选择集合。由于您直接调用mongooperations而不检索集合,因此需要使用该方法签名类型。您的意思是我应该像这样向findOne方法添加新参数(collectionName):T findOne(查询查询,类entityClass,字符串collectionName)