Morphia ID Request

I use Morphia, the Pojo builder for MongoDB, and it's hard for me to find a task that in my opinion should be very simple: getting the object by id. I can find all the objects in the collection, but I cannot understand the simple task of a query using an identifier derived from a list. I am really talking about ObjectId. If I try to display it in JSON, I will see

+5
source share
3 answers

This question seems to be incomplete.

It also seems like the answer to your question is on the Morphia QuickStart page . It seems to be so simple.

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

This way, you will definitely need more details.

+14
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);
+7

If you find by id, and the identifier is provided by the user (meaning that it can be any type of data), you should not use the solutions above.

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

This is how I implemented the method for searching 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;
}
+5
source

All Articles