Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore("MorphiaSampleDb");
Hotel hotel = new Hotel("Fairmont", 3, new Address("1 Rideau Street", "Ottawa", "K1N8S7", "Canada"));
datastore.save(hotel);
Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field("_id").equal(hotel.getId());
UpdateOperations<Hotel> datastore.createUpdateOperations(Hotel.class).set("name", "Fairmont Chateau Laurier");
datastore.update(updateQuery, ops);
QHotel qHotel = QHotel.hotel;
MorphiaQuery<Hotel> query = new MorphiaQuery<Hotel>(morphia, datastore, qHotel);
query.where(qHotel.id.eq(hotel.getId());
Query<Hotel> q = createMorphiaQuery(Hotel.class, query, datastore);
UpdateOperations<Hotel> ops = datastore.createUpdateOperations(Hotel.class).set(field(qHotel.name), "New Name");
datastore.update(q, ops);
The helper methods:
private <T> Query<T> createMorphiaQuery(Class<T> kind, MorphiaQuery<T> query, Datastore datastore)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Query<T> q = datastore.createQuery(kind);
DBObject o = (DBObject) JSON.parse(query.toString());
Method m = q.getClass().getMethod("setQueryObject", DBObject.class);
m.invoke(q, o);
return q;
}
private String field(StringPath path) {
String field = path.toString();
return field.substring(field.indexOf(".") + 1);
}
Now updating with Morphia and QueryDSL in a type safe manner is no problem anymore.
Best regards,
Andreas