Skip to content

Instantly share code, notes, and snippets.

@skingsland
Created March 4, 2016 05:32
Show Gist options
  • Save skingsland/da895e638119ece7a3e0 to your computer and use it in GitHub Desktop.
Save skingsland/da895e638119ece7a3e0 to your computer and use it in GitHub Desktop.
How to return a java.util.Map from a SQL Object query method
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import org.skife.jdbi.v2.unstable.BindIn;
@UseStringTemplate3StatementLocator
abstract class MapReturningSqlObject {
@RegisterMapper(EmailAndAccountNumberResultSetMapper.class)
@SqlQuery("select email, account_number from customer where email in (<emails>)")
abstract List<EmailAndAccountNumber> findEmailAndAccountNumbers(@BindIn("emails") Collection<String> emails);
// this is the public API method that's exposed via @Override-ing a DAO interface;
// it returns the account number from the customer table for each of the given email addresses
public Map<String, String> getAccountNumbers(Collection<String> emailAddresses) {
Map<String, String> map = new HashMap<>();
for (EmailAndAccountNumber emailAndAccountNumber : findEmailAndAccountNumbers(emailAddresses)) {
String key = emailAndAccountNumber.email;
String value = map.containsKey(key) ? "MULTIPLE_ACCOUNTS_FOUND" : emailAndAccountNumber.accountNumber;
map.put(key, value);
}
return map;
}
// JDBI *requires* this to be public!
public static class EmailAndAccountNumberResultSetMapper implements ResultSetMapper<EmailAndAccountNumber> {
@Override
public EmailAndAccountNumber map(int index, ResultSet r, StatementContext ctx) throws SQLException {
return new EmailAndAccountNumber(r.getString("email"), r.getString("account_number"));
}
}
// a helper tuple to get the results out of the SQL Object query method, because we can't register a java.util.Map mapper
private static class EmailAndAccountNumber {
final String email;
final String accountNumber;
EmailAndAccountNumber(String email, String accountNumber) {
this.email = email;
this.accountNumber = accountNumber;
}
}
}
@skingsland
Copy link
Author

As discussed in the JDBI google group thread, here is my best attempt at using a JDBI SQL Query object to fetch a java.util.Map<String, String> from a SQL query.

Github doesn't provide notification emails for comments on gists, so please reply to the thread linked above if you wish to comment, otherwise I might not see it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment