Extracting ResultSetMetaData from Spring JdbcTemplate

This is in response to a programming problem where extracting ResultSetMetaData from Spring JdbcTemplate was the requirement.

Spring provides a wrapper over ResultSet and gives us the options to map the returned RestultSet with an object of our choice.
This is easily achieved by using RowMapper interface. Below is a sample code for the usage of RowMapper:

    template.query(query, new RowMapper() {
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setAddress(rs.getString("address"));
        }
    });

This can be easily done using RowMapper if the returned ResultSet is not empty. The problem arrives when the ResultSet is empty. The ResultSet is closed and it can’t be used to fetch the ResultSetMetaData.

To get ResultSetMetaData when the returned ResultSet is empty.

Spring provides ResultSetExtractor interface, in the above example we can replace the RowMapper by the ResultSetExtractor. This is explained by a sample code below, where I the SQLCOlumn is a class defined by me.

List rsmdList = template.query(builder.toString(),new ResultSetExtractor() {
        @Override
        public ResultSetMetaData extractData(ResultSet rs) throws SQLException, DataAccessException {
            ResultSetMetaData rsmd = rs.getMetaData();
            return rsmd;
        }
     });

    ResultSetMetaData rsmd = rsmdList.get(0);

 

// here you can use athe rsmd to extract relevant information about the columns.

You can also use it as below:

    List columns = new ArrayList();
    template.query(builder.toString(),new ResultSetExtractor() {

        @Override
        public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for(int i = 1 ; i <= columnCount ; i++){
                SQLColumn column = new SQLColumn();
                column.setName(rsmd.getColumnName(i));
                column.setAutoIncrement(rsmd.isAutoIncrement(i));
                column.setType(rsmd.getColumnTypeName(i));
                column.setTypeCode(rsmd.getColumnType(i));
                column.setTableName(sqlTable.getName().toUpperCase());
                columns.add(column);
            }
            return columnCount;
        }
    });

This is how we can use the ResultSetExtractor for Extracting ResultSetMetaData from Spring JdbcTemplate on an empty ResultSet.

I have asked this question on stackoverflow.com where you can see responses from different users here.

One thought on “Extracting ResultSetMetaData from Spring JdbcTemplate”

Leave a Reply