Search in sources :

Example 1 with Query

use of org.mongodb.morphia.query.Query 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 2 with Query

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

the class DatastoreImpl method update.

@Override
@SuppressWarnings("unchecked")
public <T> UpdateResults update(final T entity, final UpdateOperations<T> operations) {
    if (entity instanceof Query) {
        return update((Query<T>) entity, operations);
    }
    final MappedClass mc = mapper.getMappedClass(entity);
    Query<?> query = createQuery(mapper.getMappedClass(entity).getClazz()).disableValidation().filter(Mapper.ID_KEY, mapper.getId(entity));
    if (!mc.getFieldsAnnotatedWith(Version.class).isEmpty()) {
        final MappedField field = mc.getFieldsAnnotatedWith(Version.class).get(0);
        query.field(field.getNameToStore()).equal(field.getFieldValue(entity));
    }
    return update((Query<T>) query, operations);
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) Query(org.mongodb.morphia.query.Query) Version(org.mongodb.morphia.annotations.Version) MappedClass(org.mongodb.morphia.mapping.MappedClass)

Example 3 with Query

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

the class Mapper method toMongoObject.

/**
     * Converts a java object to a mongo-compatible object (possibly a DBObject for complex mappings).  Very similar to {@link
     * Mapper#toDBObject}.  Used (mainly) by query/update operations.
     *
     * @param mf    the MappedField for this value
     * @param mc    the MappedClass for this value
     * @param value the value to convert
     * @return the MongoDB compatible object
     */
@SuppressWarnings("deprecation")
public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) {
    if (value == null) {
        return null;
    }
    Object mappedValue = value;
    if (value instanceof Query) {
        mappedValue = ((QueryImpl) value).getQueryObject();
    } else if (isAssignable(mf, value) || isEntity(mc)) {
        //convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity
        try {
            if (value instanceof Iterable) {
                MappedClass mapped = getMappedClass(mf.getSubClass());
                if (mapped != null && (Key.class.isAssignableFrom(mapped.getClazz()) || mapped.getEntityAnnotation() != null)) {
                    mappedValue = getDBRefs(mf, (Iterable) value);
                } else {
                    if (mf.hasAnnotation(Reference.class)) {
                        mappedValue = getDBRefs(mf, (Iterable) value);
                    } else {
                        mappedValue = toMongoObject(value, false);
                    }
                }
            } else {
                if (mf != null) {
                    Reference refAnn = mf.getAnnotation(Reference.class);
                    Class<?> idType = null;
                    if (!mf.getType().equals(Key.class) && isMapped(mf.getType())) {
                        idType = getMappedClass(mf.getType()).getMappedIdField().getType();
                    }
                    boolean valueIsIdType = mappedValue.getClass().equals(idType);
                    if (refAnn != null) {
                        if (!valueIsIdType) {
                            Key<?> key = value instanceof Key ? (Key<?>) value : getKey(value);
                            if (key != null) {
                                mappedValue = refAnn.idOnly() ? keyToId(key) : keyToDBRef(key);
                            }
                        }
                    } else if (mf.getType().equals(Key.class)) {
                        mappedValue = keyToDBRef(valueIsIdType ? createKey(mf.getSubClass(), value) : value instanceof Key ? (Key<?>) value : getKey(value));
                        if (mappedValue == value) {
                            throw new ValidationException("cannot map to Key<T> field: " + value);
                        }
                    }
                }
                if (mappedValue == value) {
                    mappedValue = toMongoObject(value, false);
                }
            }
        } catch (Exception e) {
            LOG.error("Error converting value(" + value + ") to reference.", e);
            mappedValue = toMongoObject(value, false);
        }
    } else if (mf != null && mf.hasAnnotation(Serialized.class)) {
        //serialized
        try {
            mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else if (value instanceof DBObject) {
        //pass-through
        mappedValue = value;
    } else {
        mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf));
        if (mappedValue instanceof BasicDBList) {
            final BasicDBList list = (BasicDBList) mappedValue;
            if (list.size() != 0) {
                if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) {
                    for (Object o : list) {
                        if (o instanceof DBObject) {
                            ((DBObject) o).removeField(CLASS_NAME_FIELDNAME);
                        }
                    }
                }
            }
        } else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) {
            ((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME);
        }
    }
    return mappedValue;
}
Also used : ValidationException(org.mongodb.morphia.query.ValidationException) Query(org.mongodb.morphia.query.Query) ProxiedEntityReference(org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference) Reference(org.mongodb.morphia.annotations.Reference) Serialized(org.mongodb.morphia.annotations.Serialized) IOException(java.io.IOException) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ValidationException(org.mongodb.morphia.query.ValidationException) IOException(java.io.IOException) BasicDBList(com.mongodb.BasicDBList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ReflectionUtils.getParameterizedClass(org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass) Key(org.mongodb.morphia.Key)

Example 4 with Query

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

the class AggregationTest method testCollation.

@Test
public void testCollation() {
    checkMinServerVersion(3.4);
    getDs().save(asList(new User("john doe", new Date()), new User("John Doe", new Date())));
    Query query = getDs().find(User.class).field("name").equal("john doe");
    AggregationPipeline pipeline = getDs().createAggregation(User.class).match(query);
    Assert.assertEquals(1, count(pipeline.aggregate(User.class)));
    Assert.assertEquals(2, count(pipeline.aggregate(User.class, builder().collation(Collation.builder().locale("en").collationStrength(CollationStrength.SECONDARY).build()).build())));
}
Also used : Query(org.mongodb.morphia.query.Query) Date(java.util.Date) Test(org.junit.Test)

Aggregations

Query (org.mongodb.morphia.query.Query)4 BasicDBObject (com.mongodb.BasicDBObject)2 DBObject (com.mongodb.DBObject)2 MappedClass (org.mongodb.morphia.mapping.MappedClass)2 BasicDBList (com.mongodb.BasicDBList)1 DBCollection (com.mongodb.DBCollection)1 WriteResult (com.mongodb.WriteResult)1 IOException (java.io.IOException)1 Date (java.util.Date)1 LinkedHashMap (java.util.LinkedHashMap)1 Test (org.junit.Test)1 Key (org.mongodb.morphia.Key)1 Reference (org.mongodb.morphia.annotations.Reference)1 Serialized (org.mongodb.morphia.annotations.Serialized)1 Version (org.mongodb.morphia.annotations.Version)1 MappedField (org.mongodb.morphia.mapping.MappedField)1 MappingException (org.mongodb.morphia.mapping.MappingException)1 ProxiedEntityReference (org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference)1 UpdateException (org.mongodb.morphia.query.UpdateException)1 UpdateResults (org.mongodb.morphia.query.UpdateResults)1