trainingtrains Logo

91-9990449935

 0120-4256464

RowMapper Example | Fetching records by Spring JdbcTemplate

Like ResultSetExtractor, we can use RowMapper interface to fetch the records from the database using query() method of JdbcTemplate class. In the execute of we need to pass the instance of RowMapper now.

Syntax of query method using RowMapper

RowMapper Interface

RowMapper interface allows to map a row of the relations with the instance of user-defined class. It iterates the ResultSet internally and adds it into the collection. So we don't need to write a lot of code to fetch the records as ResultSetExtractor.

Advantage of RowMapper over ResultSetExtractor

RowMapper saves a lot of code becuase it internally adds the data of ResultSet into the collection.

Method of RowMapper interface

It defines only one method mapRow that accepts ResultSet instance and int as the parameter list. Syntax of the method is given below:


Example of RowMapper Interface to show all the records of the table

We are assuming that you have created the following table inside the Oracle10g database.

Employee.java

This class contains 3 properties with constructors and setter and getters and one extra method toString().

EmployeeDao.java

It contains on property jdbcTemplate and one method getAllEmployeesRowMapper.

applicationContext.xml

The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection URL, username and password.

There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.

Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use constructor also.

Test.java

This class gets the bean from the applicationContext.xml file and calls the getAllEmployeesRowMapper() method of EmployeeDao class.