选择JPA和Spring-Data的替代方案我想用SQLite尝试使用JDBI实现我的Repository实现
存储库代码
/**
* 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
如何使这项工作受到赞赏。
答案 0 :(得分:1)
您的映射器只需要将一行映射到一个Foo对象。 JDBI将创建列表并将对象放在列表中。 即:
final List<Foo> fooList = queryHandler.createQuery(fooQuery).map(FooMapper.class).list();