【问题标题】:JDBI resultsetmapper create list of objects from query resultset?JDBI resultsetmapper 从查询结果集中创建对象列表?
【发布时间】:2017-02-28 18:15:51
【问题描述】:

选择 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();
    }
}

我很难理解如何使用 ResultSetMapper 创建 Foo 对象列表。

JDBI 文档在这方面似乎也被破坏了:

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

我们将不胜感激如何完成这项工作。

【问题讨论】:

    标签: java jdbc resultset jdbi


    【解决方案1】:

    您的映射器只需要将一行映射到一个 Foo 对象。 JDBI 将为您创建列表并将对象放入列表中。 即:

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

    【讨论】:

    • 抱歉我没看懂,能不能给个代码解决方案?
    • 只需将运行查询的代码行更改为:final List fooList = queryHandler.createQuery(fooQuery) .map(FooMapper.class).list();
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多