org.mongodb.morphia.mapping.lazy.proxy.CollectionObjectReference Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of morphia Show documentation
Show all versions of morphia Show documentation
Java Object Document Mapper for MongoDB
The newest version!
package org.mongodb.morphia.mapping.lazy.proxy;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static java.lang.String.format;
/**
* A list of proxied elements
*
* @param the type of the proxied items
*/
public class CollectionObjectReference extends AbstractReference implements ProxiedEntityReferenceList {
private static final long serialVersionUID = 1L;
private final List> listOfKeys;
/**
* Creates a CollectionObjectReference
*
* @param type the collection
* @param referenceObjClass the Class of the referenced objects
* @param ignoreMissing ignore missing referenced documents
* @param datastore the Datastore to use when fetching this reference
*/
public CollectionObjectReference(final Collection type, final Class referenceObjClass, final boolean ignoreMissing,
final Datastore datastore) {
super(datastore, referenceObjClass, ignoreMissing);
object = type;
listOfKeys = new ArrayList>();
}
@Override
//CHECKSTYLE:OFF
public void __add(final Key key) {
//CHECKSTYLE:ON
listOfKeys.add(key);
}
@Override
//CHECKSTYLE:OFF
public void __addAll(final Collection> keys) {
//CHECKSTYLE:ON
listOfKeys.addAll(keys);
}
//CHECKSTYLE:OFF
@Override
public List> __getKeysAsList() {
return Collections.unmodifiableList(listOfKeys);
}
@Override
@SuppressWarnings("unchecked")
protected void beforeWriteObject() {
if (__isFetched()) {
syncKeys();
((Collection) object).clear();
}
}
//CHECKSTYLE:ON
@Override
@SuppressWarnings("unchecked")
protected synchronized Object fetch() {
final Collection c = (Collection) object;
c.clear();
final int numberOfEntitiesExpected = listOfKeys.size();
// does not retain order:
// List retrievedEntities = p.get().getByKeys(referenceObjClass,
// (List) __getKeysAsList());
// so we do it the lousy way: FIXME
final List retrievedEntities = new ArrayList(listOfKeys.size());
for (final Key k : listOfKeys) {
T entity = (T) getDatastore().getByKey(referenceObjClass, k);
if (entity != null) {
retrievedEntities.add(entity);
}
}
if (!ignoreMissing && (numberOfEntitiesExpected != retrievedEntities.size())) {
throw new LazyReferenceFetchingException(format("During the lifetime of a proxy of type '%s', some referenced Entities"
+ " of type '%s' have disappeared from the Datastore.",
c.getClass().getSimpleName(), referenceObjClass.getSimpleName()));
}
c.addAll(retrievedEntities);
return c;
}
private void syncKeys() {
final Datastore ds = getDatastore();
listOfKeys.clear();
for (final Object e : ((Collection) object)) {
listOfKeys.add(ds.getKey(e));
}
}
}