JDBI resultsetmapper создает список объектов из набора результатов запроса?

Выбрав альтернативу JPA и Spring-Data, я хотел попробовать JDBI для своей реализации репозитория с SQLite.

Код репозитория

 /**
 * SQLite implementation of Foo Repository
 */
public class FooRepository implements FooRepository {

    private final DBI connection;

    /**
     * The constructor initialises the connection to the local SQLite file
     *
     * @param dataSource jdbc connection string e.g. "jdbc:sqlite::resource:db/foo.db"
     * @throws IllegalArgumentException when an invalid DB file is given
     */
    public FooRepository(final SQLiteDataSource dataSource) {
        checkNotNull(dataSource, "dataSource required");
        connection = new DBI(dataSource);
    }

    /**
     * Returns a list of Foo objects for a website locale in the DB

     * @return List
     * @throws SQLException error querying
     */
    @Override
    public List<Foo> getFoosByWebsiteLocale(f) throws SQLException {
        checkNotNull(websiteLocale, "websiteLocale required");

        final String fooQuery =  query...

        Handle queryHandler = connection.open();

        final List<Foo> fooList = queryHandler.createQuery(fooQuery)
            .map(FooMapper.class);

        queryHandler.close();

        return fooList;
    }
}

Сопоставитель

открытый класс FooMapper реализует ResultSetMapper {

    /**
     * Construct a Foo object from a record in the result set
     * @param index row number
     * @param resultRow row
     * @param ctx statementcontext
     * @return Foo object
     * @throws SQLException when accessing sql result set
     */
    @Override
    public Foo map(final int index, final ResultSet resultRow, final StatementContext ctx) throws SQLException {
        return Foo.builder()
                .name(resultRow.getString("foo_name"))
                .type(resultRow.getString("foo_type"))
                .build();
    }
}

Я изо всех сил пытаюсь понять, как создать список объектов Foo с помощью ResultSetMapper.

Документация JDBI также кажется нарушенной в этой области:

http://jdbi.org/maven_site/apidocs/org/skife/jdbi/v2/tweak/ResultSetMapper.html

Помощь будет оценена по тому, как сделать эту работу.


person tomaytotomato    schedule 28.02.2017    source источник


Ответы (1)


Вашему картографу нужно сопоставить только одну строку с одним объектом Foo. JDBI создаст список и поместит объекты в список для вас. То есть:

final List<Foo> fooList = queryHandler.createQuery(fooQuery).map(FooMapper.class).list();
person jenarros    schedule 28.02.2017
comment
Извините, я не понимаю, можете ли вы дать решение кода? - person tomaytotomato; 01.03.2017
comment
Просто измените строку кода, которая запускает запрос, на: final List‹Foo› fooList = queryHandler.createQuery(fooQuery) .map(FooMapper.class).list(); - person jenarros; 01.03.2017