无法使用弹簧数据从mongodb获取存储的文档

时间:2014-09-17 20:10:16

标签: java spring mongodb

我有"_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"
}

1 个答案:

答案 0 :(得分:3)

MongoDB在ID字段前添加下划线前缀,因此您应该使用Criteria.where("_id").而不是id