Created
October 29, 2015 00:59
-
-
Save dobesv/0b47e853cde23d1870a8 to your computer and use it in GitHub Desktop.
Use jackson to map jdbi beans
This file contains 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
package caltrac.db; | |
import java.sql.ResultSet; | |
import java.sql.ResultSetMetaData; | |
import java.sql.SQLException; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.skife.jdbi.v2.StatementContext; | |
import org.skife.jdbi.v2.tweak.ResultSetMapper; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
public class JacksonMapper<T> implements ResultSetMapper<T> { | |
private final Class<T> clazz; | |
private final ObjectMapper mapper = new ObjectMapper(); | |
public JacksonMapper(Class<T> clazz) { | |
super(); | |
this.clazz = clazz; | |
} | |
@Override | |
public T map(int index, ResultSet r, StatementContext ctx) throws SQLException { | |
ResultSetMetaData meta = r.getMetaData(); | |
int columnCount = meta.getColumnCount(); | |
Map<String, Object> resultsMap = new HashMap<>(); | |
for (int i = 1; i <= columnCount; ++i) { | |
String columnName = meta.getColumnName(i); | |
Object object = r.getObject(i); | |
resultsMap.put(columnName, object); | |
} | |
return mapper.convertValue(resultsMap, clazz); | |
} | |
} |
This file contains 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
package caltrac.db; | |
import org.skife.jdbi.v2.BuiltInArgumentFactory; | |
import org.skife.jdbi.v2.ResultSetMapperFactory; | |
import org.skife.jdbi.v2.StatementContext; | |
import org.skife.jdbi.v2.tweak.ResultSetMapper; | |
public class JacksonMapperFactory implements ResultSetMapperFactory { | |
@Override | |
public boolean accepts(Class type, StatementContext ctx) { | |
if (BuiltInArgumentFactory.canAccept(type)) { | |
// don't interfere with built-ins | |
return false; | |
} | |
return true; | |
} | |
@Override | |
public ResultSetMapper mapperFor(Class type, StatementContext ctx) { | |
return new JacksonMapper(type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment