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

ResultSetExtractor示例|通过Spring JdbcTemplate获取记录

我们可以使用 JdbcTemplate 类的 query()方法轻松地从数据库中获取记录,我们需要传递ResultSetExtractor的实例。

使用ResultSetExtractor的查询方法的语法

public T query(String sql,ResultSetExtractor<T> rse)

ResultSetExtractor接口

ResultSetExtractor 接口可用于从数据库中获取记录。它接受一个ResultSet并返回列表。

ResultSetExtractor接口的方法

它仅定义一个方法ResultResult实例作为参数接受。该方法的语法如下:

public T extractData(ResultSet rs)throws SQLException,DataAccessException

显示表的所有记录的ResultSetExtractor接口示例

我们假设您已经在Oracle10g数据库中创建了以下表。

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

Employee.java

此类包含3一个带有构造函数,setter和getter的属性。它定义了一个额外的toString()方法。

package 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

它包含属性jdbcTemplate和一种方法getAllEmployees。

package 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;
public class EmployeeDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
    this.template = template;
}
public List<Employee> getAllEmployees(){
 return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
    @Override
     public List<Employee> extractData(ResultSet rs) throws SQLException,
            DataAccessException {
        List<Employee> list=new ArrayList<Employee>();
        while(rs.next()){
        Employee e=new Employee();
        e.setId(rs.getInt(1));
        e.setName(rs.getString(2));
        e.setSalary(rs.getInt(3));
        list.add(e);
        }
        return list;
        }
    });
  }
}

applicationContext.xml

DriverManagerDataSource usado para conter informações sobre o banco de dados, como o nome da classe do driver, a URL de conexão, o nome de usuário e a senha.

No JdbcTemplate do tipo DriverManagerDataSource há um método chamado datasource A propriedade. Portanto, precisamos fornecer uma referência ao objeto DriverManagerDataSource para a propriedade do provedor de dados no JdbcTemplate.

Aqui, usamos o objeto JdbcTemplate na classe EmployeeDao, portanto, passamos por meio do método setter, mas você também pode usar o construtor.

<?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

Este tipo obtém Beans do arquivo applicationContext.xml e chama o método getAllEmployees() da classe EmployeeDao.

package 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.getAllEmployees();
    for(Employee e:list)
        System.out.println(e);
    }
}