How to map JDBI SQL query result to Map using annotations?

4 weeks ago 17
ARTICLE AD BOX

I'm using JDBI v3 and need to execute a query that returns events with their associated interests. I want to map the result directly to Map<Long, List<Interest>> where the key is the event ID and the value is the list of interests for that event.

@SqlQuery(""" SELECT e.id AS event_id, i.id AS interest_id, i.name AS interest_name, i.category_id AS category_id FROM event e LEFT JOIN event_interest ei ON e.id = ei.event_id LEFT JOIN interest i ON i.id = ei.interest_id WHERE e.id IN (<eventIds>) """) Map<Long, List<Interest>> findInterestsByEventIds(@BindList Set<Long> eventIds);

Interest model:

public class Interest { private final Long id; private final String name; private final Long categoryId; }

Problem: I know about @UseRowReducer annotation, but it seems designed to work with Collection types rather than Map. The JDBI documentation doesn't clearly show how to map results to Map<Long, List<Interest>>.

What I've tried/considered:

Using @UseRowReducer - but it appears to be for Collection results

Using Multimap - but I'm not sure how to implement this with JDBI annotations

Manual mapping in service layer - but I'd prefer to handle this at the database layer

Specific question: How can I configure JDBI to directly return Map<Long, List<Interest>> using annotations in the Dao interface? I'd prefer a solution that:

Works with annotation-based configuration (not fluent API)

Doesn't require casting or additional processing in the service layer

Handles the one-to-many relationship properly

If a Multimap approach is needed, please show how to implement it with JDBI annotations.

Read Entire Article