Spring JDBC SimpleJdbcCall類示例

org.springframework.jdbc.core.SimpleJdbcCall類是表示對存儲過程或存儲函數的調用的多線程,可重用的對象。 它提供元數據處理以簡化訪問基本存儲過程/函數所需的代碼。 所有需要提供的是程序/函數的名稱和包含執行調用時參數的Map對象。 提供的參數的名稱將與創建存儲過程時聲明的輸入和輸出參數相匹配。

使用到的 Student 表的結構如下 -

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

類的聲明

以下是org.springframework.jdbc.core.SimpleJdbcCall接口的聲明 -

public class SimpleJdbcCall
   extends AbstractJdbcCall
      implements SimpleJdbcCallOperations

以下示例將演示如何使用Spring的SimpleJdbcCall對象調用存儲過程。通過調用存儲過程來讀取Student表中的一條記錄。傳遞一個學生編號作爲參數並讀取學生記錄。

語法

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord");
SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
Map<String, Object> out = jdbcCall.execute(in);
Student student = new Student();
student.setId(id);
student.setName((String) out.get("out_name"));
student.setAge((Integer) out.get("out_age"));

在上代碼中,

  • jdbcCall - SimpleJdbcCall對象來表示存儲過程。
  • in - SqlParameterSource對象將參數傳遞給存儲過程。
  • student - 學生(Student)對象。
  • out - Map對象來表示存儲過程調用結果的輸出。

實例項目

要了解上述與Spring JDBC相關的概念,下面我們編寫一個使用SimpleJdbcCall進行存儲過程調用。打開Eclipse IDE,並按照以下步驟創建一個Spring應用程序,這裏創建一個名稱爲:SimpleJdbcCall 的項目。

步驟說明

  1. 參考第一個Spring JDBC項目來創建一個Maven項目 - http://www.yiibai.com/springjdbc/first\_application.html
  2. 更新bean配置並運行應用程序。

完整的項目結構如下所示 -

Spring

要了解如何調用數據庫中的存儲過程,請創建以下MySQL存儲過程,該過程需要學生ID作爲參數,並使用OUT參數返回相應的學生姓名和年齡。所以首先打開MySQL命令提示符,並在test數據庫中創建一個存儲過程 -

DELIMITER $$

DROP PROCEDURE IF EXISTS `TEST`.`getRecord` $$
CREATE PROCEDURE `TEST`.`getRecord` (
IN in_id INTEGER,
OUT out_name VARCHAR(20),
OUT out_age  INTEGER)
BEGIN
   SELECT name, age
   INTO out_name, out_age
   FROM Student where id = in_id;
END $$

DELIMITER ;

以下是Maven配置文件:pom.xml的代碼內容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>SimpleJdbcCall</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>SimpleJdbcCall</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>

以下是數據訪問對象接口文件:StudentDAO.java的內容:

package com.yiibai;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {
    /**
     * This is the method to be used to initialize database resources ie.
     * connection.
     */
    public void setDataSource(DataSource ds);

    /**
     * This is the method to be used to create a record in the Student table.
     */
    public void create(String name, Integer age);

    /**
     * This is the method to be used to list down all the records from the
     * Student table.
     */
    public List<Student> listStudents();

    /**
     * This is the method to be used to list down a record from the Student
     * table corresponding to a passed student id.
     */
    public Student getStudent(Integer id);
}

以下是文件:Student.java的代碼內容:

package com.yiibai;

public class Student {
    private Integer age;
    private String name;
    private Integer id;

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }
}

以下是文件:StudentMapper.java的代碼內容:

package com.yiibai;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {
    public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Student();
        student.setId(rs.getInt("id"));
        student.setName(rs.getString("name"));
        student.setAge(rs.getInt("age"));
        return student;
    }
}

實現類StudentJDBCTemplate.java實現了定義的DAO接口 - StudentDAO.java,以下是文件:StudentJDBCTemplate.java的代碼內容:

package com.yiibai;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    SimpleJdbcInsert jdbcInsert;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
        this.jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("Student");
    }

    public void create(String name, Integer age) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", name);
        parameters.put("age", age);
        jdbcInsert.execute(parameters);
        System.out.println("Created Record Name = " + name + " Age = " + age);
        return;
    }

    public List<Student> listStudents() {
        String SQL = "select * from Student";
        List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
        return students;
    }

    public Student getStudent(Integer id) {
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord");

        SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
        Map<String, Object> out = jdbcCall.execute(in);

        Student student = new Student();
        student.setId(id);
        student.setName((String) out.get("out_name"));
        student.setAge((Integer) out.get("out_age"));
        return student;
    }
}

以下是文件:MainApp.java的代碼內容:

package com.yiibai;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.StudentJDBCTemplate;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");

        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

        System.out.println("------Records Creation--------");
        studentJDBCTemplate.create("Maxsu", 21);
        studentJDBCTemplate.create("Curry", 22);
        studentJDBCTemplate.create("Suzend", 23);

        System.out.println("------SimpleJdbcCall--------");
        Student student = studentJDBCTemplate.getStudent(1);

        System.out.print("ID : " + student.getId());
        System.out.print(", Name : " + student.getName());
        System.out.println(", Age : " + student.getAge());

        System.out.println("------Listing Multiple Records--------");
        List<Student> students = studentJDBCTemplate.listStudents();
        for (Student record : students) {
            System.out.print("ID : " + record.getId());
            System.out.print(", Name : " + record.getName());
            System.out.println(", Age : " + record.getAge());
        }
    }
}

以下是文件:application-beans.xml的代碼內容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

    <!-- Initialization for data source -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <!-- Definition for studentJDBCTemplate bean -->
    <bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

注意: application-beans.xml 文件的位置是:{workspace}/fistapp/src/main/java 目錄,如果放置錯了,程序可能會因爲找不到此配置文件而出錯。

完成創建源代碼和bean和數據庫連接信息的文件配置後,運行應用程序。這裏先簡單說明一下運行的步驟,在項目名稱(SimpleJdbcCall)上點擊右鍵,在彈出的菜單中選擇:【Run As】-> 【Maven test】

在運行測試成功後,應該會輸出類似以下內容(含有 BUILD SUCCESS 的信息) 。
接下來,點擊類文件:MainApp.java 選擇【Run As】->【Java Application】,如果應用程序一切正常,這將打印以下結果:

------Records Creation--------
Created Record Name = Maxsu Age = 21
Created Record Name = Curry Age = 22
Created Record Name = Suzend Age = 23
------SimpleJdbcCall--------
ID : 1, Name : Maxsu, Age : 21
------Listing Multiple Records--------
ID : 1, Name : Maxsu, Age : 21
ID : 2, Name : Curry, Age : 22
ID : 3, Name : Suzend, Age : 23