Question

I have to dynamically execute queries which will come from database.The query has dynamic fields,which needs to be converted into map as key value pairs and send to view.For ex one query may return only one fields and other may return more than two field of multiple rows.I have to write code in such way that it will work for n no.of fields and return it as map using spring jdbc.

Was it helpful?

Solution

Spring offers two ways to solve your problem.

Approach 1: use queryForList method from JdbcTemplate class. this will return List of Map populated by column names as key , and DB record as value. you have to manualy iterate over the list. each map object inside the list represents a single row in resultset. example :

List<Map<String, Object>> result = jdbcTemplate.queryForList(query, new Object[]{123});

        Iterator items = result.iterator();

        while(items.hasNext()){
            Map<String, Object> row = (Map<String, Object>) items.next();
            System.out.println(row);
        }

Approach 2 : this dosen't exactly match your requirements, but little faster than the first approach also more coding involved. you can use queryForRowSet method.

    SqlRowSet rowSet = jdbcTemplate.queryForRowSet(query,  new Object[]{3576});

    int columnCount  = rowSet.getMetaData().getColumnCount();
    System.out.println(columnCount);

    while(rowSet.next()){

        for(int id =1 ; id <= columnCount ; id ++){
            System.out.println(rowSet.getString(id)) ;
            // your custom logic goes here 

        }

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top