📜  Spring – ResultSetExtractor

📅  最后修改于: 2022-05-13 01:54:37.644000             🧑  作者: Mango

Spring – ResultSetExtractor

ResultSetExtractor是一个用于从数据库中获取记录的接口。它是 JDBC 模板的 query() 方法使用的回调接口,我们需要传递 ResultSetExtractor 的实例以获取数据。

ResultSetExtractor 的 query() 方法的语法:

public T query(String sqlQuery, ResultSetExtractor resultSetExtractor)

为了使用 ResultSetExtractor 获取数据,我们需要实现 ResultSetExtractor 接口并为其方法提供定义。它只有一种方法。即, extractData() 将 ResultSet 的实例作为参数并返回列表。

extractData() 方法的语法:

public T extractData(ResultSet resultSet) throws SQL Exception, DataAccessException

例子

在此示例中,我们将使用 ResultSetExtractor 从 Student 表中提取所有记录。对于本教程,我们将为 Student 表使用以下模式。

Student(id INT, name VARCHAR(45), department VARCHAR(45))

分步实施:

第 1 步:创建表

在这一步中,我们将创建一个学生表来存储学生的信息。对于本教程,我们将假设您已在数据库中创建了下表。

CREATE TABLE STUDENT(
id INT,
name VARCHAR(45),
department VARCHAR(45));

创建表后,我们将在表中插入以下数据。

INSERT INTO STUDENT VALUES(1, "geek", "computer science");

第 2 步:添加依赖项

在这一步中,我们会将 maven 依赖项添加到我们的应用程序中。将以下依赖项添加到您的 pom.xml

XML

  4.0.0
  com.geeksforgeeks
  ResultSetExtractorExample
  0.0.1-SNAPSHOT 
   
  
     
          
          
            org.springframework
            spring-jdbc
            5.3.16
        
         
        
        
                org.springframework
                spring-context
                5.0.8.RELEASE
        
 
        
            mysql
            mysql-connector-java
            5.1.44
        
 
  
 


Java
public class Student {
   
    // Member variables
    private int id;
    private String name;
    private String department;
     
    // Getters and Setters method
    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 String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
     
    // toString() method
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";
    }   
}


Java
import java.util.List;
 
import com.geeksforgeeks.model.Student;
 
public interface StudentDao {
    // This method will return all
    // the details of the students
    public List getAllStudentDetails();
 
}


Java
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 com.geeksforgeeks.model.Student;
 
public class StudentDaoImpl implements StudentDao{
     
    // Defining JdbcTemplate as member variable in order
    // to use the query() method of the JdbcTemplate's class
    private JdbcTemplate jdbcTemplate;
     
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
 
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    // This method will return the list
    // of all the details of student
    public List getAllStudentDetails() {
         
        // Implementation of ResultSetExtractor interface
        return jdbcTemplate.query("SELECT * FROM student", new ResultSetExtractor>() {
             
            // extractData() is ResultSetExtractor
            // interface's method
            public List extractData(ResultSet rs) throws SQLException, DataAccessException {
                List studentDetailList = new ArrayList();
                while(rs.next()) {
                    Student student = new Student();
                    // 1, 2 and 3 are the indices of the data present
                    // in the database respectively
                    student.setId(rs.getInt(1));
                    student.setName(rs.getString(2));
                    student.setDepartment(rs.getString(3));
                    studentDetailList.add(student);
                }
                return studentDetailList;
            }
             
        });
    }
}


XML
 
 
   
     
         
         
         
         
     
       
     
         
     
   
     
         
     
   


Java
import java.util.List;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.geeksforgeeks.dao.StudentDaoImpl;
import com.geeksforgeeks.model.Student;
 
public class TestResultSetExtractor {
 
    public static void main(String[] args) {
         
        // Reading the application-context file using
        // class path of spring context xml file
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
         
        // Spring check the blueprint for studentDao bean
        // from application-context.xml file and return it
        StudentDaoImpl studentDaoImpl = (StudentDaoImpl)context.getBean("studentDao");
         
        // Getting student data
        List studentDetailList = studentDaoImpl.getAllStudentDetails();
         
        for(Student index : studentDetailList) {
            System.out.println(index);
        }
    }
}


第三步:创建模型类

现在,我们将为我们的学生创建一个模型班。此类将具有三个成员变量 id、name 和部门。我们还将定义它的 getters 和 setters 方法以及 toString() 方法。

Java

public class Student {
   
    // Member variables
    private int id;
    private String name;
    private String department;
     
    // Getters and Setters method
    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 String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
     
    // toString() method
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";
    }   
}

第四步:创建 Dao 接口

现在,我们将创建一个接口并将其命名为StudentDao ,我们将使用它来访问数据存储数据库中的数据。我们需要定义getAllStudentDetails()方法,该方法将返回学生的所有详细信息。

Java

import java.util.List;
 
import com.geeksforgeeks.model.Student;
 
public interface StudentDao {
    // This method will return all
    // the details of the students
    public List getAllStudentDetails();
 
}

步骤 5:为 Dao 接口创建一个实现类

在这一步中,我们将创建一个实现类StudentDaoImpl。Java该类实现了 StudentDao 接口,并为 StudentDao 接口的getAllStudentDetails()方法提供了定义。在这个类中,我们还将实现ResultSetExtractor接口并提供其extractData()方法的定义。

Java

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 com.geeksforgeeks.model.Student;
 
public class StudentDaoImpl implements StudentDao{
     
    // Defining JdbcTemplate as member variable in order
    // to use the query() method of the JdbcTemplate's class
    private JdbcTemplate jdbcTemplate;
     
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
 
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    // This method will return the list
    // of all the details of student
    public List getAllStudentDetails() {
         
        // Implementation of ResultSetExtractor interface
        return jdbcTemplate.query("SELECT * FROM student", new ResultSetExtractor>() {
             
            // extractData() is ResultSetExtractor
            // interface's method
            public List extractData(ResultSet rs) throws SQLException, DataAccessException {
                List studentDetailList = new ArrayList();
                while(rs.next()) {
                    Student student = new Student();
                    // 1, 2 and 3 are the indices of the data present
                    // in the database respectively
                    student.setId(rs.getInt(1));
                    student.setName(rs.getString(2));
                    student.setDepartment(rs.getString(3));
                    studentDetailList.add(student);
                }
                return studentDetailList;
            }
             
        });
    }
}

第 6 步:Bean 配置

在这一步中,我们将创建 spring 配置文件并将其命名为application-contex.xml 。我们将配置我们的 bean 并使用 factory-method 属性来创建 bean。为了与数据库建立连接,我们需要以下信息用户名、密码、数据库连接、URL 和驱动程序类名称。所有这些信息都包含在DriverManagerDataSource类中,它具有返回Java类型连接的getConnection()方法。我们在 StudentDao 类中使用 JdbcTemplate 的实例,并使用 setter 注入方法传递它。

XML

 
 
   
     
         
         
         
         
     
       
     
         
     
   
     
         
     
   

第 7 步:创建实用程序类

现在,我们将创建一个 Utility 类来测试我们的应用程序。为此创建一个新类并将其命名为TestResultSetExtractor。 Java并将以下代码添加到其中。

Java

import java.util.List;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.geeksforgeeks.dao.StudentDaoImpl;
import com.geeksforgeeks.model.Student;
 
public class TestResultSetExtractor {
 
    public static void main(String[] args) {
         
        // Reading the application-context file using
        // class path of spring context xml file
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
         
        // Spring check the blueprint for studentDao bean
        // from application-context.xml file and return it
        StudentDaoImpl studentDaoImpl = (StudentDaoImpl)context.getBean("studentDao");
         
        // Getting student data
        List studentDetailList = studentDaoImpl.getAllStudentDetails();
         
        for(Student index : studentDetailList) {
            System.out.println(index);
        }
    }
}

第 8 步:输出

现在,我们将运行我们的应用程序。

输出

输出