Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Morphia by Id

I am using Morphia, the Pojo mapper for MongoDB, and I find difficult a task that in my view should be very simple: getting an object by id. I am able to find all the objects in a collection but I cannot figure out the simple task of querying using an id I got from the list. I am actually talking about the ObjectId. If I try to render it in JSON I see

like image 332
msciab Avatar asked Dec 17 '10 06:12

msciab


3 Answers

This question seems incomplete.

It also seems like the answer to you question is on the Morphia QuickStart page. Seems to be as simple as follows.

Datastore ds = morphia.createDatastore("testDB");
String hotelId = ...; // the ID of the hotel we want to load
// and then map it to our Hotel object
Hotel hotel = ds.get(Hotel.class, hotelId);

So you'll definitely need more details.

like image 62
Gates VP Avatar answered Sep 23 '22 14:09

Gates VP


Datastore ds = morphia.createDatastore("testDB");
String hotelId = "516d41150364a6a6697136c0"; // the ID of the hotel we want to load
ObjectId objectId = new ObjectId(hotelId);
// and then map it to our Hotel object
Hotel hotel = ds.get(Hotel.class, objectId);
like image 36
Pavel B Avatar answered Sep 23 '22 14:09

Pavel B


If you're finding by id and the id is provided by the user (means that it could be whatever type of data), you shouldn't use the solutions given above.

As explained in the documentation, an ObjectId consists of 12 bytes, so if you pass something else to new ObjectId(myValue), your code will throw an IllegalArgumentException.

Here is how I implemented the method to find by id :

public Model findById(String id) throws NotFoundException {
    if (!ObjectId.isValid(id)) {
        throw new NotFoundException();
    }

    ObjectId oid = new ObjectId(id);
    Model m = datastore().find(Model.class).field("_id").equal(oid).get();
    if (m == null) {
        throw new NotFoundException();
    }
    return m;
}
like image 33
c4k Avatar answered Sep 21 '22 14:09

c4k