Saturday, June 1, 2013

SingleColumnRowMapper & ColumnMapRowMapper examples in Spring

Spring JDBC includes two default implementations of RowMapper - SingleColumnRowMapper and ColumnMapRowMapper. Below are the sample usages of those row mappers.

There are lots of situations when you just want to select one column or only a selected set of columns in your application and to write custom row mapper implementations for these scenarios doesn't seem right. In these scenarios, we can make use of the spring provided row mapper implementations.


This class implements RowMapper interface. As the name suggests, this class can be used to retrieve a single value from the database as a java.util.List. The list contains the column values one per each row.

In the below code snippet, the type of the result value for each row is specified by the constructor argument. It can also be specified by invoking the setRequiredType(Class<T> requiredType) method.

public List getFirstName(int userID)

  String sql = "select firstname from users where user_id = " + userID; 
  SingleColumnRowMapper rowMapper = new SingleColumnRowMapper(String.class); 
  List firstNameList = (List) getJdbcTemplate().query(sql, rowMapper); 

  for(String firstName: firstNameList) 
  return firstNameList; 

More information on the class and its methods can be found in the below spring javadoc link.



ColumnMapRowMapper class can be used to retrieve more than one column from a database table. This class also implements RowMapper interface.This class creates a java.util.Map for each row, representing all columns as key-value pairs: one entry for each column, with the column name as key.

public List<Map<String, Object>> getUserData(int userID)
  String sql = "select firstname, lastname, dept from users where userID = ? ";
  ColumnMapRowMapper rowMapper = new ColumnMapRowMapper();
  List<Map<String, Object>> userDataList =  getJdbcTemplate().query(sql, rowMapper, userID);

  for(Map<String, Object> map: userDataList){
      System.out.println("FirstName = " + map.get("firstname"));
      System.out.println("LastName = " + map.get("lastname"));
      System.out.println("Department = " + map.get("dept"));
  return userDataList;

More information on the class and its methods can be found in the below spring javadoc link.

No comments: