JDBI, retrieve data with sql query in a custom object (constructor) instead of Map

Therefore, when we use the JDBI to query from the database, it gets it into the type Map<String, Object> .

I want to get it as my custom object (constructor) instead of Map<String, Object> .

 DBI dbi = establishConnection(url, userName, passWord); Handle handle = dbi.open(); List<Map<String, Object>> rs = handle.select("select * from sometable"); 

Instead, I want to use:

 List<customizedObject> rs = handle.select("select * from sometable"); 

Where the customizedObject class is an object that contains all the properties of the column with it.

Is there any way to do this? I found some relative documentation, but I cannot understand its implementation.

http://jdbi.org/sql_object_api_queries/

+8
java sql jdbi
source share
1 answer

Also see the previous page in the documentation, which shows how to associate your Handle or DBI with mappers.

Essentially, you need a mapper to convert a ResultSet into your desired object and interface to access the mapper.

Assume a minimal example. A cartographer must first be provided:

 public class CustomizedObjectMapper implements ResultSetMapper<customizedObject> { @Override public customizedObject map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new customizedObject(r.getString("uuid"), r.getString("other_column")); } } 

Then we need an interface to determine which request provides the data that is passed to the mapper class. One line of results leads to one call to CustomizedObjectMapper.map(...) :

 @RegisterMapper(CustomizeObjectMapper.class) public interface CustomizeObjectQuery { @SqlQuery("Select uuid, other_column from schema.relation") List<customizedObject> get(); } 

Finally, the objects can be obtained: List<customizedObject> test = dbi.open(CustomizeObjectQuery.class).get() .

You can also combine components on an individual basis and omit the interface: dbi.open().createQuery("Select uuid, other_colum from schema.relation").map(new EventMapper()).list()

+11
source share

All Articles