0

I have a method in my DAO which looks like this

ProductDao.java

public List<Document> getAllProducts() {
    return mongoCollection.find().into(new ArrayList<Document>());
}

What I would like instead is

//return a list of Product instead of Document
public List<Product> getAllProducts() {
    return mongoCollection.find().into(new ArrayList<Product>());
}

pom.xml

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

How can I achieve this?

2 Answers 2

1

There are few java libs that can help you with it:

Morhpia - http://code.google.com/p/morphia/

Spring Data for MongoDB - http://www.springsource.org/spring-data/mongodb

Also, you can do something like:

public List<Product> getAllProducts() {
    DBCursor cur = mongoCollection.find();
    List<Product> products = new ArrayList<Product>();
    while(cur.hasNext()) {
        products.add(cur.next());
    }
    return products;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Keen on trying out Morphia. Looks promising. Is it a subproject of MongoDB ?
Yes it is a sub project, Morphia is built on top of the original mongodb java driver. Its like a wrapper around it.
The problem with this is that it opens a connection every time the method is called, do you have any solution for this?
1

look into MongoJack.

Mongojack maps Java objects to MongoDB documents. Based on the Jackson JSON mapper, Mongojack allows you to easily handle your mongo documents as POJOs

Comments

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.