Created
September 12, 2011 20:34
-
-
Save criminy/1212323 to your computer and use it in GitHub Desktop.
Lazy List Utilities useful for lazy-loading of DAO collections.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RepositoryInstance repositoryInstance; //some Repository which has findById. | |
List<T> lazyList = LazyListUtil.idListToLazyList(jdbcTemplate.queryForList("select foreign_key from join_table where primary_key = ?",new Object[]{id},String.class),repositoryInstance)); | |
// The only query run so far "select foreign key from join_table where primary_key = ?" . the others aren't run until we use lazyList, which would be inside RepositoryInstance. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import com.google.common.base.Function; | |
import com.google.common.base.Supplier; | |
import com.google.common.base.Suppliers; | |
import com.google.common.collect.ImmutableList; | |
import com.google.common.collect.Lists; | |
public class LazyListUtil { | |
public static <T> Function<Supplier<T>, T> supplyFunction() { | |
return new Function<Supplier<T>, T>() { | |
public T apply(Supplier<T> supplier) { | |
return supplier.get(); | |
} | |
}; | |
} | |
public static <T> List<T> idListToLazyList(List<String> ids, final Repository<T> repo) { | |
return Lists.transform((List<Supplier<T>>) | |
ImmutableList.copyOf( | |
Lists.transform( | |
ids, | |
new Function<String, Supplier<T>>() { | |
public Supplier<T> apply(String key) { | |
return Suppliers.memoize(Suppliers.compose( | |
new Function<String,T>() { | |
@Override | |
public T apply(String arg0) { | |
return repo.findById(arg0); | |
} | |
}, | |
Suppliers.ofInstance(key))); | |
} | |
})), | |
LazyListUtil.<T>supplyFunction()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment