Search code examples
javamongodbjakarta-eemorphia

Java MongoDB Morphia: find a object by ObjectId id


I am using Morphia and a DAO Class. I have a Class with an Id ObjectId:

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class GeoProfileVo extends ResponseVo implements Serializable{

    private static final long serialVersionUID = -4975628041316056892L;

    @Id private ObjectId id;

    private String email;
    private String name;
    private String city;

    //Getters, Setters and toString
}

GeoProfileDAO:

public class GeoProfileDAO extends BasicDAO<GeoProfileVo, ObjectId>{

    public GeoProfileDAO(Morphia morphia, MongoClient mongoClient, String db) {
        super(mongoClient, morphia, db);
    }

    public GeoProfileVo findByNme(String name){
        return getDs().find(GeoProfileVo.class, "name", name).get();
    }

    //Here is the problem
    public GeoProfileVo findById (ObjectId id){
        //return getDs().find(GeoProfileVo.class).field("id").equal(id).get();
        return getDs().get(GeoProfileVo.class, id);
    }

    public ObjectId saveGeoProfile(GeoProfileVo geoProfileVo){
        return (ObjectId) getDs().save(geoProfileVo).getId();
    }
}

My Service:

public class GeolocationService implements Serializable{

    private static final long serialVersionUID = 2071937170723089158L;

    /** The Constant log. */
    private static final Logger LOGGER = Logger.getLogger(GeolocationService.class.getName());

    private MongoClient mongoClient;
    private GeoProfileDAO geoProfileDAO;

    public GeolocationService(){
        super();
        LOGGER.info("[GeolocationService - Constructor] - init");

        //mongoClient:
        mongoClient = new MongoClient("localhost",27017);

        //morphia:
        Morphia morphia = new Morphia();
        morphia.map(GeoProfileVo.class);

        //morphia dao:
        geoProfileDAO = new GeoProfileDAO(morphia, mongoClient, "mydb");
    }

    public GeoProfileVo updateGeoProfile(GeoProfileVo geoProfileVo) throws GeoProfileNotFoundException{
        LOGGER.info("[GeolocationService - updateGeoProfile] - init");
        long currentSystemTime=System.currentTimeMillis();

        if(geoProfileVo == null){
            LOGGER.error("[GeolocationService - updateGeoProfile] - geoProfileVo cannot be null");
            throw new IllegalArgumentException();
        }
        if(geoProfileVo.getId() == null){
            LOGGER.error("[GeolocationService - updateGeoProfile] - ID cannot be null");
            throw new IllegalArgumentException();
        }

        GeoProfileVo geoProfileVoEntity = geoProfileDAO.findById(geoProfileVo.getId());
        if(geoProfileVoEntity==null){
            LOGGER.error("[GeolocationService - updateGeoProfile] - geoProfileVo not found in BD");
            throw new GeoProfileNotFoundException();
        }

        LOGGER.debug("[GeolocationService - updateGeoProfile] - Finish Timing:"+(System.currentTimeMillis()-currentSystemTime));
        return geoProfileDAO.updateGeoProfile(geoProfileVo);
    }

    //CRUD

}

I am able to search by email, name or city, insert a object in BD but I am not able to search by id. In google I only find information about a String id and I don´t find much information about id type ObjectId. when I try to find by the ObjectId Id, doesn´t find nothing and returns null.

For example, when I find by email, returns:

{
       "id":    {
          "timestamp": 1432028968,
          "machineIdentifier": 9913253,
          "processIdentifier": 7516,
          "counter": 8215016
       },
       "email": "[email protected]",
       "name": "john",
       "city": "Madrid"
}

I call a WS that call a createGeoProfile Service with the same Object with the same id but in Eclipse IDE, the "id" is different in each call. Maybe the problem is here but I don´t understand it.

How do I find an object with id type ObjectId?


Solution

  • He solution was return a ObjectId.toString() when I insert a object in BD. I understand that this objectId is similar to a Hash, so when I want to find by Id, I cannot sent an ObjectId type because this ObjectId changes. For this reason, we must return a toString() (this part was that I didn´t undestand).

    With this String, we instantiate an ObjectId that we use it for find by id:

    public GeoProfileVo findById (String id){
        ObjectId oid = new ObjectId(id);
        return getDs().find(GeoProfileVo.class).field("id").equal(oid).get();
    }
    
    public String saveGeoProfile(GeoProfileVo geoProfileVo){
        return getDs().save(geoProfileVo).getId().toString();
    }
    

    In the end, to avoid having an ObjectId type that I will not use it, I change the Id in my GeoProfileVo to type String.

    @Id private String id;
    

    Now, the response of FindById, contains the id in String type:

    {
       "id": "555c44e39743a5141c00d0a1",
       "email": "[email protected]",
       "name": "john",
       "city": "Madrid"
    }