Spring – RowMapper Interface with Example
RowMapper Example | Fetching records by Spring JdbcTemplate
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:
public T mapRow(ResultSet rs, int rowNumber)throws SQLException
Example of RowMapper Interface to show all the records of the table
We are assuming that you have created the following table inside the Mysql database.
This class contains 3 properties with constructors and setter and getters and one extra method toString().
package rowmapper;
public class Employee {
private int id;
private String name;
private float salary;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
EmployeeDao.java
It contains on property jdbcTemplate and one method getAllEmployeesRowMapper.
package rowmapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class EmployeeDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployeesRowMapper(){
return template.query("select * from employee",new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
return e;
}
});
}
}
This Java code defines a class named EmployeeDao
that interacts with a database using the Spring Framework's JDBC (Java Database Connectivity) template. It provides a method getAllEmployeesRowMapper
to retrieve a list of employee records from a database table named "employee" and maps each row to an Employee
object using a RowMapper
. Here's a breakdown of the code:
Imports:
- The code begins with several import statements that include necessary classes and interfaces for working with databases and the Spring Framework's JDBC support.
Class Declaration:
- The
EmployeeDao
class is declared as a public class.
- The
Private JdbcTemplate Field:
- Inside the
EmployeeDao
class, there is a private field namedtemplate
of typeJdbcTemplate
. This field will be used to interact with the database.
- Inside the
Setter Method:
- The class contains a setter method named
setTemplate
for setting thetemplate
field. This method allows you to inject aJdbcTemplate
instance into theEmployeeDao
class, typically done through Spring's dependency injection.
- The class contains a setter method named
getAllEmployeesRowMapper
Method:This method retrieves all employee records from the "employee" table in the database and maps each row to an
Employee
object using aRowMapper
.It uses the
template.query
method to execute an SQL query ("select * from employee"
) and fetch the results.Inside the
query
method:- The first argument is the SQL query string.
- The second argument is an instance of
RowMapper<Employee>
, which is an anonymous inner class that implements theRowMapper
interface.
In the
mapRow
method of theRowMapper
interface:- It creates a new
Employee
object. - It retrieves data from the
ResultSet
and sets theid
,name
, andsalary
properties of theEmployee
object. - Finally, it returns the populated
Employee
object.
- It creates a new
Spring Framework:
- This code assumes that you are using the Spring Framework, as it relies on Spring's
JdbcTemplate
and other Spring-related imports and conventions.
- This code assumes that you are using the Spring Framework, as it relies on Spring's
To use this EmployeeDao
class, you would typically configure it as a Spring bean and inject a JdbcTemplate
instance with the appropriate database connection details. Then, you can call the getAllEmployeesRowMapper
method to fetch a list of employee records from the database.
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.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name='ds'>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springJdbcs" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="rawmapper.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the getAllEmployeesRowMapper() method of EmployeeDao class.
package rowmapper;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployeesRowMapper();
for(Employee e:list)
System.out.println(e);
}
}
Comments
Post a Comment