我有"_id" : ObjectId("5449567cdf97f277c50d1ce2")
的文档,但在null
使用id
尝试获取时,我得到findOne
。怎么解决?
主要
public class MongoDBJDBC {
public static void main( String args[] ){
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
ProductService productService = context.getBean(ProductService.class);
Product product = productService.get("5449567cdf97f277c50d1ce2"); // null here
}
}
服务
@Service
public class ProductService {
@Autowired
private ProductDao productDao;
@Autowired
private ProductPropertiesDao productPropertiesDao;
public void add(Product product) {
productDao.save(product);
}
public void update(Product product) {
productDao.save(product);
}
public Product get(String id) {
return productDao.get(id);
}
道
@Repository
public class ProductDao {
@Autowired
private MongoOperations mongoOperations;
public Product get(String id) {
return mongoOperations.findOne(Query.query(Criteria.where("id").is(new ObjectId(id))), Product.class);
}
}
实体
@Document(collection = Product.COLLECTION_NAME)
public class Product implements Serializable {
public Product() {
}
public static final String COLLECTION_NAME = "product";
@Id
private String _id;
private String name;
}
文档
{
"_id" : ObjectId("5449567cdf97f277c50d1ce2"),
"name" : "product"
}
答案 0 :(得分:3)
MongoDB在ID字段前添加下划线前缀,因此您应该使用Criteria.where("_id").
而不是id
。