How to manage a large dataset using Spring MySQL and RowCallbackHandler

后端 未结 3 2027
-上瘾入骨i
-上瘾入骨i 2020-12-10 15:47

I\'m trying to go over each row of a table in MySQL using Spring and a JdbcTemplate. If I\'m not mistaken this should be as simple as:

JdbcTemplate template         


        
3条回答
  •  無奈伤痛
    2020-12-10 16:25

    Here's a Spring solution based on the answer provided by BalusC.

    class StreamingStatementCreator implements PreparedStatementCreator {
        private final String sql;
    
        public StreamingStatementCreator(String sql) {
            this.sql = sql;
        }
    
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            final PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            statement.setFetchSize(Integer.MIN_VALUE);
            return statement;
        }
    }
    

    Somewhere in your code:

    DataSource dataSource = ...;
    RowCallbackHandler rowHandler = ...;
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.query(new StreamingStatementCreator("SELECT * FROM huge_table"), rowHandler);
    

提交回复
热议问题