Search in sources :

Example 1 with UpdateResults

use of org.mongodb.morphia.query.UpdateResults in project morphia by mongodb.

the class Employee method main.

public static void main(final String[] args) throws UnknownHostException {
    final Morphia morphia = new Morphia();
    // tell morphia where to find your classes
    // can be called multiple times with different packages or classes
    morphia.mapPackage("org.mongodb.morphia.example");
    // create the Datastore connecting to the database running on the default port on the local host
    final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
    datastore.getDB().dropDatabase();
    datastore.ensureIndexes();
    final Employee elmer = new Employee("Elmer Fudd", 50000.0);
    datastore.save(elmer);
    final Employee daffy = new Employee("Daffy Duck", 40000.0);
    datastore.save(daffy);
    final Employee pepe = new Employee("Pepé Le Pew", 25000.0);
    datastore.save(pepe);
    elmer.getDirectReports().add(daffy);
    elmer.getDirectReports().add(pepe);
    datastore.save(elmer);
    Query<Employee> query = datastore.find(Employee.class);
    final List<Employee> employees = query.asList();
    Assert.assertEquals(3, employees.size());
    List<Employee> underpaid = datastore.find(Employee.class).filter("salary <=", 30000).asList();
    Assert.assertEquals(1, underpaid.size());
    underpaid = datastore.find(Employee.class).field("salary").lessThanOrEq(30000).asList();
    Assert.assertEquals(1, underpaid.size());
    final Query<Employee> underPaidQuery = datastore.find(Employee.class).filter("salary <=", 30000);
    final UpdateOperations<Employee> updateOperations = datastore.createUpdateOperations(Employee.class).inc("salary", 10000);
    final UpdateResults results = datastore.update(underPaidQuery, updateOperations);
    Assert.assertEquals(1, results.getUpdatedCount());
    final Query<Employee> overPaidQuery = datastore.find(Employee.class).filter("salary >", 100000);
    datastore.delete(overPaidQuery);
}
Also used : MongoClient(com.mongodb.MongoClient) Morphia(org.mongodb.morphia.Morphia) Datastore(org.mongodb.morphia.Datastore) UpdateResults(org.mongodb.morphia.query.UpdateResults)

Example 2 with UpdateResults

use of org.mongodb.morphia.query.UpdateResults in project morphia by mongodb.

the class DatastoreImpl method updateFirst.

@Override
@Deprecated
public <T> UpdateResults updateFirst(final Query<T> query, final T entity, final boolean createIfMissing) {
    if (getMapper().getMappedClass(entity).getMappedVersionField() != null) {
        throw new UnsupportedOperationException("updateFirst() is not supported with versioned entities");
    }
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject dbObj = mapper.toDBObject(entity, involvedObjects);
    final UpdateResults res = update(query, dbObj, createIfMissing, false, getWriteConcern(entity));
    // update _id field
    if (res.getInsertedCount() > 0) {
        dbObj.put(Mapper.ID_KEY, res.getNewId());
    }
    postSaveOperations(singletonList(entity), involvedObjects, getCollection(entity), false);
    return res;
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateResults(org.mongodb.morphia.query.UpdateResults) LinkedHashMap(java.util.LinkedHashMap)

Example 3 with UpdateResults

use of org.mongodb.morphia.query.UpdateResults in project morphia by mongodb.

the class DatastoreImpl method merge.

@Override
@SuppressWarnings("unchecked")
public <T> Key<T> merge(final T entity, final WriteConcern wc) {
    T unwrapped = entity;
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject dbObj = mapper.toDBObject(unwrapped, involvedObjects);
    final Key<T> key = mapper.getKey(unwrapped);
    unwrapped = ProxyHelper.unwrap(unwrapped);
    final Object id = mapper.getId(unwrapped);
    if (id == null) {
        throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
    }
    // remove (immutable) _id field for update.
    final Object idValue = dbObj.get(Mapper.ID_KEY);
    dbObj.removeField(Mapper.ID_KEY);
    WriteResult wr;
    final MappedClass mc = mapper.getMappedClass(unwrapped);
    final DBCollection dbColl = getCollection(unwrapped);
    // try to do an update if there is a @Version field
    wr = tryVersionedUpdate(dbColl, unwrapped, dbObj, idValue, new InsertOptions().writeConcern(wc), mc);
    if (wr == null) {
        final Query<T> query = (Query<T>) createQuery(unwrapped.getClass()).filter(Mapper.ID_KEY, id);
        wr = update(query, new BasicDBObject("$set", dbObj), false, false, wc).getWriteResult();
    }
    final UpdateResults res = new UpdateResults(wr);
    if (res.getUpdatedCount() == 0) {
        throw new UpdateException("Nothing updated");
    }
    dbObj.put(Mapper.ID_KEY, idValue);
    postSaveOperations(Collections.<Object>singletonList(entity), involvedObjects, dbColl, false);
    return key;
}
Also used : Query(org.mongodb.morphia.query.Query) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateResults(org.mongodb.morphia.query.UpdateResults) LinkedHashMap(java.util.LinkedHashMap) MappingException(org.mongodb.morphia.mapping.MappingException) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) WriteResult(com.mongodb.WriteResult) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateException(org.mongodb.morphia.query.UpdateException)

Example 4 with UpdateResults

use of org.mongodb.morphia.query.UpdateResults in project morphia by mongodb.

the class DatastoreImpl method tryVersionedUpdate.

private <T> WriteResult tryVersionedUpdate(final DBCollection dbColl, final T entity, final DBObject dbObj, final Object idValue, final InsertOptions options, final MappedClass mc) {
    WriteResult wr;
    if (mc.getFieldsAnnotatedWith(Version.class).isEmpty()) {
        return null;
    }
    final MappedField mfVersion = mc.getMappedVersionField();
    final String versionKeyName = mfVersion.getNameToStore();
    Long oldVersion = (Long) mfVersion.getFieldValue(entity);
    long newVersion = nextValue(oldVersion);
    dbObj.put(versionKeyName, newVersion);
    if (idValue != null && newVersion != 1) {
        final Query<?> query = find(dbColl.getName(), entity.getClass()).disableValidation().filter(Mapper.ID_KEY, idValue).enableValidation().filter(versionKeyName, oldVersion);
        final UpdateResults res = update(query, dbObj, new UpdateOptions().bypassDocumentValidation(options.getBypassDocumentValidation()).writeConcern(options.getWriteConcern()));
        wr = res.getWriteResult();
        if (res.getUpdatedCount() != 1) {
            throw new ConcurrentModificationException(format("Entity of class %s (id='%s',version='%d') was concurrently updated.", entity.getClass().getName(), idValue, oldVersion));
        }
    } else {
        wr = saveDocument(dbColl, dbObj, options);
    }
    return wr;
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) ConcurrentModificationException(java.util.ConcurrentModificationException) WriteResult(com.mongodb.WriteResult) Version(org.mongodb.morphia.annotations.Version) UpdateResults(org.mongodb.morphia.query.UpdateResults) DBCollectionUpdateOptions(com.mongodb.client.model.DBCollectionUpdateOptions)

Example 5 with UpdateResults

use of org.mongodb.morphia.query.UpdateResults in project morphia by mongodb.

the class DatastoreImpl method update.

@Override
public <T> UpdateResults update(final Query<T> query, final UpdateOperations<T> operations, final UpdateOptions options) {
    DBCollection dbColl = query.getCollection();
    // TODO remove this after testing.
    if (dbColl == null) {
        dbColl = getCollection(query.getEntityClass());
    }
    final MappedClass mc = getMapper().getMappedClass(query.getEntityClass());
    final List<MappedField> fields = mc.getFieldsAnnotatedWith(Version.class);
    DBObject queryObject = query.getQueryObject();
    if (operations.isIsolated()) {
        queryObject.put("$isolated", true);
    }
    if (!fields.isEmpty()) {
        operations.inc(fields.get(0).getNameToStore(), 1);
    }
    final BasicDBObject update = (BasicDBObject) ((UpdateOpsImpl) operations).getOps();
    if (LOG.isTraceEnabled()) {
        LOG.trace(format("Executing update(%s) for query: %s, ops: %s, multi: %s, upsert: %s", dbColl.getName(), queryObject, update, options.isMulti(), options.isUpsert()));
    }
    return new UpdateResults(dbColl.update(queryObject, update, enforceWriteConcern(options, query.getEntityClass()).getOptions()));
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateResults(org.mongodb.morphia.query.UpdateResults)

Aggregations

UpdateResults (org.mongodb.morphia.query.UpdateResults)16 Test (org.junit.Test)10 BasicDBObject (com.mongodb.BasicDBObject)5 DBObject (com.mongodb.DBObject)4 DBCollection (com.mongodb.DBCollection)3 LinkedHashMap (java.util.LinkedHashMap)3 MappedClass (org.mongodb.morphia.mapping.MappedClass)3 MappedField (org.mongodb.morphia.mapping.MappedField)3 WriteResult (com.mongodb.WriteResult)2 Date (java.util.Date)2 Datastore (org.mongodb.morphia.Datastore)2 MongoClient (com.mongodb.MongoClient)1 DBCollectionUpdateOptions (com.mongodb.client.model.DBCollectionUpdateOptions)1 ConcurrentModificationException (java.util.ConcurrentModificationException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 ObjectId (org.bson.types.ObjectId)1 Ignore (org.junit.Ignore)1 Morphia (org.mongodb.morphia.Morphia)1