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

ResultSetExtractor 예제|Spring JdbcTemplate를 통해 레코드 가져오기

사용할 수 있습니다. JdbcTemplate JdbcTemplate 클래스의 query()ResultSetExtractor 인스턴스를 전달하여 데이터베이스에서 레코드를 쉽게 가져올 수 있습니다.

ResultSetExtractor를 사용하는 쿼리 메서드의 문법

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

ResultSetExtractor 인터페이스

ResultSetExtractor 인터페이스는 데이터베이스에서 레코드를 가져오기 위해 사용될 수 있습니다. ResultSet을 받아서 목록을 반환합니다.

ResultSetExtractor 인터페이스의 메서드

그것은 ResultSet 인스턴스를 파라미터로 받는 하나의 메서드만 정의합니다. 메서드 문법은 다음과 같습니다:

public T extractData(ResultSet rs) throws SQLException, DataAccessException

ResultSetExtractor 인터페이스 예제로 테이블의 모든 레코드를 출력합니다

Oracle에서 이미 설치되어 있다고 가정합니다.10g 데이터베이스에서 다음 테이블을 생성했습니다.

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 템플릿;
public void setTemplate(JdbcTemplate 템플릿) {
    this.템플릿 = 템플릿;
}
public List<Employee> getAllEmployees(){
 return 템플릿.쿼리("select * from employee", new ResultSetExtractor<List<Employee>>(){
    @Override
     public List<Employee> extractData(ResultSet rs) throws SQLException,
            DataAccessException {
        List<Employee> 리스트 = 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);
        리스트.add(e);
        }
        리스트를 반환합니다;
        }
    );
  }
}

applicationContext.xml

DriverManagerDataSource 데이터베이스에 대한 정보를 포함하는 데 사용됩니다. 예를 들어, 드라이버 클래스 이름, 연결 URL, 사용자 이름 및 비밀번호.

DriverManagerDataSource 타입의 JdbcTemplate 클래스에는 이름이 datasource 의 속성입니다. 따라서 우리는 DriverManagerDataSource 객체의 참조를 데이터 소스 속성에 제공해야 합니다.

여기서 우리는 EmployeeDao 클래스에서 JdbcTemplate 객체를 사용하므로 setter 메서드를 통해 전달했지만, 생성자를 사용할 수도 있습니다.

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

이 클래스는 applicationContext.xml 파일에서 Bean을 가져오고 EmployeeDao 클래스의 getAllEmployees() 메서드를 호출합니다.

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);
    }
}