Search in sources :

Example 1 with QueryException

use of dev.morphia.query.QueryException in project morphia by mongodb.

the class ReferenceCodec method encodeId.

/**
 * Encodes a value
 *
 * @param value the value to encode
 * @param model the mapped class of the field type
 * @return the encoded value
 * @morphia.internal
 */
private Object encodeId(Object value, PropertyModel model) {
    Object idValue;
    final String valueCollectionName;
    if (value instanceof Key) {
        idValue = ((Key<?>) value).getId();
        String collectionName = ((Key<?>) value).getCollection();
        Class<?> type = ((Key<?>) value).getType();
        if (collectionName == null || type == null) {
            throw new QueryException("Missing type or collection information in key");
        }
        valueCollectionName = collectionName;
    } else {
        idValue = mapper.getId(value);
        if (idValue == null) {
            if (!mapper.isMappable(value.getClass())) {
                return value;
            }
            throw new QueryException("No ID value found on referenced entity.  Save referenced entities before defining references to" + " them.");
        }
        valueCollectionName = mapper.getEntityModel(value.getClass()).getCollectionName();
    }
    Reference annotation = model.getAnnotation(Reference.class);
    if (annotation != null && !annotation.idOnly()) {
        idValue = new DBRef(valueCollectionName, idValue);
    }
    return idValue;
}
Also used : QueryException(dev.morphia.query.QueryException) SetReference(dev.morphia.mapping.experimental.SetReference) ListReference(dev.morphia.mapping.experimental.ListReference) MapReference(dev.morphia.mapping.experimental.MapReference) SingleReference(dev.morphia.mapping.experimental.SingleReference) MorphiaReference(dev.morphia.mapping.experimental.MorphiaReference) Reference(dev.morphia.annotations.Reference) DBRef(com.mongodb.DBRef) Key(dev.morphia.Key)

Aggregations

DBRef (com.mongodb.DBRef)1 Key (dev.morphia.Key)1 Reference (dev.morphia.annotations.Reference)1 ListReference (dev.morphia.mapping.experimental.ListReference)1 MapReference (dev.morphia.mapping.experimental.MapReference)1 MorphiaReference (dev.morphia.mapping.experimental.MorphiaReference)1 SetReference (dev.morphia.mapping.experimental.SetReference)1 SingleReference (dev.morphia.mapping.experimental.SingleReference)1 QueryException (dev.morphia.query.QueryException)1