How to set fetchSize for concrete query?

你。 提交于 2019-12-11 04:25:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!