我的模型类看起来像这样:
package io.springBoot.ProductionDetails;
import org.springframework.data.annotation.Id;
public class ProductionDetailsModel {
//Created an entity for ProductDetails
@Id
private String productId;
private String name;
private String description;
private String image; //Alway's in Binary data
private String sellerUserId;
public ProductionDetailsModel() {
}
//Constructors
public ProductionDetailsModel( String productId, String name, String description, String image, String sellerUserId) {
super();
this.productId = productId;
this.name = name;
this.description = description;
this.image = image;
this.sellerUserId = sellerUserId;
}
//Getter and Setter Methods for objects
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getSellerUserId() {
return sellerUserId;
}
public void setSellarUserId(String sellerUserId) {
this.sellerUserId = sellerUserId;
}
I am able to get single document based on this query:
public void getProductDetails(String Id) {
return productdetialsRepository.findOne(id);
}
我想传递一个参数:sellerUserId并从Mongodb获取所有基于sellerUserId的文档。我怎样才能实现这一目标?请帮忙吗?
在ProductDetailsRepository
中添加这样的方法 public interface ProductdetialsRepository extends MongoRepository<ProductionDetailsModel, String>{
List< ProductionDetailsModel> findAllBySellerUserId(final String sellerUserId);
}
在我的控制器中,我添加了
@RequestMapping(method=RequestMethod.GET, path = "/{sellerUserId}")
void getProductDetails(@PathVariable String sellerUserId) {
System.out.println(sellerUserId);
productdetialsRepository.findAllBySellerUserId(sellerUserId);
}
我也尝试过这个
Query query = new Query();
query.addCriteria(Criteria.where("id").is(sellerUserId));
List<ProductionDetailsModel> productionDetailsList = productdetialsRepository.find(query ProductionDetailsModel.class);
但我得到空指针Exception任何人都可以请你帮忙吗?
答案 0 :(得分:1)
您需要在存储库接口中编写方法
List< ProductionDetailsModel> findAllBySellerUserId(final String sellerUserId);
并在serviceImpl类中调用此方法
List<ProductionDetailsModel> findAllBySellerUserId(final String sellerUserId){
return productdetialsRepository.findBySellerUserId(sellerUserId);
}
使用mongo和spring的其他更好的解决方案是使用mongoOperations(由spring框架提供)
Query query = new Query();
query.addCriteria(Criteria.where("id").is(sellerUserId));
List<ProductionDetailsModel> productionDetailsList = mongoOperation.find(your query, ProductionDetailsModel.class);
答案 1 :(得分:0)
在ProductDetailsRepository
中添加这样的方法List<ProductDetails> findBySellerUserId(String sellerUserId)
Spring数据将根据方法名称制定查询并获得结果。