package com.dooapp.gaedo.finders.collections;
import java.util.Collection;
import java.util.List;
import com.dooapp.gaedo.finders.FieldInformer;
import com.dooapp.gaedo.finders.FinderCrudService;
import com.dooapp.gaedo.finders.Informer;
import com.dooapp.gaedo.finders.QueryBuilder;
import com.dooapp.gaedo.finders.QueryExpression;
import com.dooapp.gaedo.finders.expressions.Expressions;
import com.dooapp.gaedo.finders.id.IdBasedService;
import com.dooapp.gaedo.finders.root.InformerFactory;
import com.dooapp.gaedo.properties.Property;
/**
* Collection service providing id lookup capabilities
* @author ndx
*
* @param <DataType>
* @param <InformerType>
*/
public class IdSupportingCollectionBackedFinderService<DataType, InformerType extends Informer<DataType>> extends
DefaultCollectionBackedFinderService<DataType, InformerType> implements
FinderCrudService<DataType, InformerType>, IdBasedService<DataType> {
/**
* Properties are stored as a list for easier indexed access
*/
private List<Property> idProperties;
public IdSupportingCollectionBackedFinderService(
Class<DataType> containedClass, Class<InformerType> informerClass,
InformerFactory factory, List<Property> idProperties) {
super(containedClass, informerClass, factory);
this.idProperties = idProperties;
}
@Override
public DataType findById(final Object... id) {
return find().matching(new QueryBuilder<InformerType>() {
@Override
public QueryExpression createMatchingExpression(
InformerType informer) {
QueryExpression returned = null;
for(int index=0; index<id.length; index++) {
FieldInformer fieldInformer = getInformer().get(idProperties.get(index).getName());
QueryExpression propertyEquality = fieldInformer.equalsTo(id[index]);
if(returned==null) {
returned = propertyEquality;
} else {
returned = Expressions.and(returned, propertyEquality);
}
}
return returned;
}
}).getFirst();
}
@Override
public Collection<Property> getIdProperties() {
return idProperties;
}
}