Selecting multiple columns from a table

710 views
Skip to first unread message

Brian Moroz

unread,
Dec 4, 2013, 9:29:43 PM12/4/13
to jd...@googlegroups.com
I'm almost certain this question has been raised before, but I can't seem to find a clear and concise answer: Is a result mapper required when selecting multiple columns from a table?

To be clear, this seems to work just fine: 
@SqlQuery("select id from something where id = :id")
List<String> SelectId(@Bind("id") int id)

This does not work:
@SqlQuery("select id,name from something where id = :id")
[Return Type] SelectId(@Bind("id") int id)

Perhaps I've missed it, but from the literature I've reviewed it seems that one must create a "result mapper" for this. Is this true?

Thank you.



Steven Schlansker

unread,
Dec 5, 2013, 3:18:12 AM12/5/13
to jd...@googlegroups.com
On Dec 4, 2013, at 6:29 PM, Brian Moroz <brim...@gmail.com> wrote:

> I'm almost certain this question has been raised before, but I can't seem to find a clear and concise answer: Is a result mapper required when selecting multiple columns from a table?
>

You use a result mapper whether one column or many columns are involved. JDBI picks a result mapper
based on the return type of a method, and there are many default mappers for trivial “single string column -> java.lang.String”
sorts of mappings.

There’s very few multi-column mappings that make sense as a default for a library. IIRC, one of these is “any number of columns -> Map<String, Object>” where the returned map is by column name.

> To be clear, this seems to work just fine:
> @SqlQuery("select id from something where id = :id")
> List<String> SelectId(@Bind("id") int id)
>

Uses the provided-by-default StringMapper, which takes the first column and returns it as a String.

> This does not work:
> @SqlQuery("select id,name from something where id = :id")
> [Return Type] SelectId(@Bind("id") int id)

Depends totally on what [Return Type] is and whether there is a mapper registered :)

>
> Perhaps I've missed it, but from the literature I've reviewed it seems that one must create a "result mapper" for this. Is this true?
>

Yes, you can create custom mappers (instances of ResultSetMapper) and then either specify them for use directly (via Query.map or annotations @Mapper), or you can register custom “auto-mappers” (instances of ResultSetMapperFactory) that look at return types via Handle.registerMapper or annotations like @RegisterMapperFactory / @RegisterMapper.

Hope that helps,
Steven

Brian Moroz

unread,
Dec 5, 2013, 1:43:17 PM12/5/13
to jd...@googlegroups.com
Great. Thank you.

There seems to be enough back-end machinery to tailor result mappers fairly quickly.
Reply all
Reply to author
Forward
0 new messages