English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

RowMapper example|Get records through Spring JdbcTemplate

Just like ResultSetExtractor, we can use the RowMapper interface to JdbcTemplate class query()The method retrieves records from the database. During execution, we now need to pass an instance of RowMapper.

Syntax of query methods using RowMapper

public T query(String sql,RowMapper<T> rm)

RowMapper interface

RowMapper The interface allows the use of instances of user-defined classes to map rows. It internally iterates over the ResultSet and adds them to the collection. Therefore, we do not need to write a lot of code to get the records as ResultSetExtractor.

RowMapper is better than ResultSetExtractor

RowMapper can save a lot of code because

Methods of the RowMapper interface

It only defines a method MapRow, which accepts ResultSet instance and int as parameter list. The syntax of the method is as follows:

public T mapRow(ResultSet rs, int rowNumber)throws SQLException

An example of the RowMapper interface to display all records of the table

We assume that you have already installed Oracle10g database created the following table.

create table employee(
id number(10)
name varchar2(100),
salary number(10)
);

Employee.java

This class includes3a class with a constructor, setter and getter properties, and an additional toString() method.

paquete com.w3codebox;
public class Employee {
private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
//getters and setters
public String toString(){
    return id+" "+name+" "+salary;
}
}

EmployeeDao.java

It includes properties jdbcTemplate and a method getAllEmployeesRowMapper.

paquete com.w3codebox;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
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;
    }
    });
}
}

applicationContext.xml

DriverManagerDataSource utilizado para contener información sobre la base de datos, como el nombre de la clase del controlador, la URL de conexión, el nombre de usuario y la contraseña.

En la clase JdbcTemplate de tipo DriverManagerDataSource hay un método llamado datasource Las propiedades. Por lo tanto, necesitamos proporcionar una referencia al objeto DriverManagerDataSource para las propiedades del proveedor de datos en la clase JdbcTemplate.

Aquí, hemos utilizado el objeto JdbcTemplate en la clase EmployeeDao, por lo tanto, lo pasamos a través del método setter, pero también puede usar el constructor.

<?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 id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"> />
<property name="url" value="jdbc:oracle:thin:@localhost:>1521:xe" />
<property name="username" value="system"> />
<property name="password" value="oracle"> />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.w3codebox.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>

Test.java

Esta clase obtiene el Bean desde el archivo applicationContext.xml y llama al método getAllEmployeesRowMapper() de la clase EmployeeDao.

paquete com.w3codebox;
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);
}
}