问题
I want to set fetchSize only for one query and I can't find appropriate api for that.
my code looks like this:
jdbcTemplate.query(query, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {...}
);
How can I pass fetchSize to the query ?
回答1:
This can be done using PreparedStatementSetter
(JavaDoc)
Given the query
select * from mytable where user_id > ?
You can use
jdbcTemplate.query(query,
new PreparedStatementSetter() {
@Override
public void setValues(final PreparedStatement ps) throws SQLException {
ps.setInt(1, userId);
ps.setFetchSize(500);
}
},
new RowCallbackHandler() {
@Override
public void processRow(final ResultSet rs) throws SQLException {
...
}
});
Or in a more compact form
jdbcTemplate.query(
query,
ps -> {
ps.setInt(1, userId);
ps.setFetchSize(500);
},
rs -> { ... }
);
Keep in mind that
Implementations are responsible for setting any necessary parameters.
SQL with placeholders will already have been supplied.
For a single resulting object, use the
public <T> T query(String sql,
PreparedStatementSetter pss,
ResultSetExtractor<T> rse) throws DataAccessException;
method. For example
jdbcTemplate.query(
query,
new ArgumentPreparedStatementSetter(new Object[] {balanceId}),
rs -> {
final String field1 = rs.getString("field1");
// Get other fields and construct the resulting object
return new YourClass(field1, ...);
}
);
来源:https://stackoverflow.com/questions/55318272/how-to-set-fetchsize-for-concrete-query