Querying Morphia by Id

后端 未结 3 540
傲寒
傲寒 2021-01-13 11:09

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 object

3条回答
  •  温柔的废话
    2021-01-13 11:57

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

提交回复
热议问题