0

I have document with "_id" : ObjectId("5449567cdf97f277c50d1ce2") but I am getting null when trying to get it by id using findOne. How to solve it?

main

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

@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);
    }

dao

    @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);
    }
}

entity

@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;
   }

document

{
    "_id" : ObjectId("5449567cdf97f277c50d1ce2"),
    "name" : "product"
}

1 Answer 1

3

MongoDB adds underline prefix before ID field, so you should use Criteria.where("_id"). instead of just id.

Sign up to request clarification or add additional context in comments.

2 Comments

Seems like it solves problem but I get right after org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type org.bson.types.ObjectId to type int. What might it be?
Try to use .is(id)) instead of new ObjectId(id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.