Description
Hello,
I have been using java-dataloader for some time now and I found it very useful. Here is one small feedback:
I find the current BatchLoader
functional interface is often inconvenient:
CompletionStage<List<V>> load(List<K> keys)
The input is a list of keys and the output is a list that has to match 1 to 1 with the list of keys. In real world data fetching scenarios, it's rare to do a query that returns 1 to 1 matches. For example, let's assume that I want to load Users from a database, I could probably use a query that looks like this:
SELECT * FROM User WHERE id IN (keys)
This kind of queries are very common when using batch loaders, however, this won't return a 1 to 1 match. If one of the users does not exist, the result will not contain it. This means that in order to use this query in a BatchLoader
, I have to first create a map, and then return a List of that crossed with the original keys. For example:
List<User> users = database.query("SELECT * FROM User WHERE id IN keys");
Map<Integer, User> userByKey = users.stream().collect(toMap(User::getId, Function.identity()));
List<User> result = keys.stream().map(userByKey::get).collect(toList());
return result;
I think all this bolier plate code can be reduced if an alternative BatchLoader
is provided that returns a Map
instead:
CompletionStage<Map<K, V>> load(List<K> keys)
What do you think?