我目前正在开展迁移项目,将数据从旧数据库迁移到新数据库(请不要问我为什么要通过Java应用程序,这是客户需要的。)
我现在正在更新一些初始代码。我正在改变的一件事是使用Spring的JdbcTemplate
,而不是那里的锅炉板代码。
不幸的是,我还没有找到在JdbcTemplate
上执行分页查询的方法,类似于旧代码:
Statement statement = getConnection().createStatement(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statement.setFetchDirection(ResultSet.FETCH_FORWARD);
statement.setFetchSize(1000);
return statement.executeQuery();
getConnection()
只返回一个Connection
对象,用简单的JDBC代码创建(它不是SessionFactory
或框架实现的一部分)。
然后我会遍历结果集,一次映射一行。有谁知道是否有一种简单的方法可以使用JdbcTemplate
实现相同的功能?
TIA
答案 0 :(得分:6)
我认为此类应用程序的自然选择是Spring Batch(阅读令人印象深刻的Features page)
以下是与您相关的部分:
<强> ItemReaders and ItemWriters > DataBase 强>
特别是JdbcPagingItemReader
答案 1 :(得分:1)
你的意思是......像这样?
SimpleJdbcTemplate template = new SimpleJdbcTemplate(dataSource);
List<String> result = template.query("SELECT name FROM people WHERE id > ?",
new RowMapper<String>() {
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("name");
}
}, 666
);
或者这个:
template.getJdbcOperations().query("SELECT name FROM people WHERE id > ?",
new Object[] { 666 },
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
System.out.println(String.format(
"Got '%s'", rs.getString("name")));
}
}
);