2017-02-28 184 views
0

选择了替代JPA和Spring的数据我想尝试JDBI我的仓库实现使用SQLiteJDBI resultsetmapper从查询结果集创建对象列表?

库代码

/** 
* 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美孚对象的列表。

的JDBI文档也出现在这个区域被打破:

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

帮助将就如何使这项工作可以理解的。

回答

1

您的映射器只需要将一行映射到一个Foo对象。 JDBI将创建列表并将这些对象放入列表中。 I.e .:

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

对不起,我不明白,你可以给一个代码解决方案? – kaleeway

+0

只要改变的代码运行查询以行:最终列表 fooList = queryHandler.createQuery(fooQuery) .MAP(FooMapper.class).LIST(); – jenarros