Spring JDBC

Implementing RowMapper in Spring with Example

In this tutorial, we are implementing RowMapper class to map our domain objects. We then use this class to write fetch methods that return custom model objects.

Implementing RowMapper

Spring provides a RowMapper interface for mapping a single row of a ResultSet to an object. It can be used for both single and multiple row queries. It is parameterized as of Spring 3.0.

public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum)
throws SQLException;
}

An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object, but don’t need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate.

Typically used either for JdbcTemplate’s query methods or for out parameters of stored procedures. RowMapper objects are typically stateless and thus reusable; they are an ideal choice for implementing row-mapping logic in a single place.

Alternatively, consider subclassing MappingSqlQuery from the jdbc.object package: Instead of working with separate JdbcTemplate and RowMapper objects, you can build executable query objects (containing row-mapping logic) in that style.

Say for example, when we are selecting records from an employee table, we will iterate over the result set to get the individual values which won’t be ideal for situations, especially in Java where we want to map records from a database to individual Java objects. Also the question of re-usability comes into the picture as the above code doesn’t represent for getting itself re-used. Spring Row Mapper interfaces come into the rescue for such situations.

Querying for Single Row:

Here’s two ways to query or extract a single row record from database, and convert it into a model class(Employee).

1. Custom RowMapper:

In general, It’s always recommended to implement the RowMapper interface to create a custom RowMapper to suit your needs..

package com.dineshonjava.sdnext.jdbc.utils;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public class EmployeeMapper implements RowMapper {  
 public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {  
  Employee employee = new Employee();  
  employee.setEmpid(rs.getInt("empid"));  
  employee.setName(rs.getString("name"));  
  employee.setAge(rs.getInt("age"));  
  employee.setSalary(rs.getLong("salary"));  
  return employee;  
 }  
}  

Pass it to queryForObject() method, the returned result will call your custom mapRow() method to match the value into the property.

public Employee getEmployee(Integer empid) {
   String SQL = "SELECT * FROM Employee WHERE empid = ?";
   Employee employee = (Employee) jdbcTemplateObject.queryForObject(SQL, new Object[]{empid}, new EmployeeMapper());
    return employee;
}

2. BeanPropertyRowMapper:

In Spring 2.5, comes with a handy RowMapper implementation called ‘BeanPropertyRowMapper’, which can maps a row’s column value to a property by matching their names. Just make sure both the property and column has the same name, e.g property ‘empid’ will match to column name ‘EMPID’ or with underscores ‘EMP_ID’.

public Employee getEmployee(Integer empid) {
   String SQL = "SELECT * FROM Employee WHERE empid = ?";
   Employee employee = (Employee) jdbcTemplateObject.queryForObject(SQL, new Object[]{empid}, new BeanPropertyRowMapper(Employee.class));
    return employee;
}

Querying for Multiple Rows:

Now, query or extract multiple rows from database, and convert it into a List.

1. Map it manually:

In mutiple return rows, RowMapper is not supported in queryForList() method, you need to map it manually.

public List<Employee> findAll(){
  String sql = "SELECT * FROM Employee";
 
 List employees= new ArrayList();
 
 List rows = getJdbcTemplate().queryForList(sql);
 for (Map row : rows) {
  Employee employee = new Employee();
  employee.setEmpid((Integer)(row.get("EMPID")));
  employee.setName((String)row.get("NAME"));
  employee.setAge((Integer)row.get("AGE"));
                employee.setSalary((Long)row.get("SALARY"));
  employees.add(employee);
 }
  return employees;
}

2. BeanPropertyRowMapper:

The simplest solution is using the BeanPropertyRowMapper class.

public List findAll(){
  String sql = "SELECT * FROM Employee";
  List employees= getJdbcTemplate().query(sql,
   new BeanPropertyRowMapper(Employee.class));
  return employees;
}
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago