Spring JDBC StoredProcedure类示例

Spring JDBC StoredProcedure类示例

org.springframework.jdbc.core.StoredProcedure类是RDBMS存储过程的对象抽象的超类。这个类是抽象的,目的是让子类将提供一个用于调用的类型化方法,该方法委托给所提供的execute(java.lang.Object ...)方法。继承的sql属性是RDBMS中存储过程的名称。

使用到的 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.StoredProcedure接口的声明 -

public abstract class StoredProcedure
   extends SqlCall

以下示例将演示如何使用spring的StoredProcedure调用存储过程。通过调用存储过程来读取Student表中的一条记录,将传递一个学生编号(ID)并接收学生记录信息。

语法

class StudentProcedure extends StoredProcedure{
   public StudentProcedure(DataSource dataSource, String procedureName){
      super(dataSource,procedureName);
      declareParameter(new SqlParameter("in_id", Types.INTEGER));
      declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
      declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
      compile();
   }

   public Student execute(Integer id){
      Map<String, Object> out = super.execute(id);
      Student student = new Student();
      student.setId(id);
      student.setName((String) out.get("out_name"));
      student.setAge((Integer) out.get("out_age"));
      return student;      
   }
}

在上代码中,

  • StoredProcedure - StoredProcedure对象用于表示存储过程。
  • StudentProcedure - StudentProcedure对象扩展了StoredProcedure,将输入,输出变量和映射结果给Student对象。
  • student - Student对象。

实例项目

要了解上述与Spring JDBC相关的概念,下面我们编写一个使用调用存储过程的示例。打开Eclipse IDE,并按照以下步骤创建一个Spring应用程序,这里创建一个名称为:StoredProcedure 的项目。

步骤说明

  1. 参考第一个Spring JDBC项目来创建一个Maven项目 - http://www.zyiz.net/springjdbc/first_application.html
  2. 更新bean配置并运行应用程序。

完整的项目结构如下所示 -

要了解如何使用StoredProcedure,请参考以下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.zyiz</groupId>
    <artifactId>StoredProcedure</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>StoredProcedure</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.zyiz;

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.zyiz;

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.zyiz;

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.zyiz;

import java.sql.Types;
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.RowMapper;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.object.SqlQuery;
import org.springframework.jdbc.object.StoredProcedure;

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

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

    public Student getStudent(Integer id) {
        StudentProcedure studentProcedure = new StudentProcedure(dataSource, "getRecord");
        return studentProcedure.execute(id);
    }

    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";
        SqlQuery<Student> sqlQuery = new SqlQuery<Student>() {

            @Override
            protected RowMapper<Student> newRowMapper(Object[] parameters, Map<?, ?> context) {
                return new StudentMapper();
            }
        };
        sqlQuery.setDataSource(dataSource);
        sqlQuery.setSql(sql);
        List<Student> students = sqlQuery.execute();
        return students;
    }
}

class StudentProcedure extends StoredProcedure {
    public StudentProcedure(DataSource dataSource, String procedureName) {
        super(dataSource, procedureName);
        declareParameter(new SqlParameter("in_id", Types.INTEGER));
        declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
        declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
        // compile();
    }

    public Student execute(Integer id) {
        Map<String, Object> out = super.execute(id);
        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.zyiz;

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zyiz.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("----Listing Record with ID = 1 -----");
        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.zyiz.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

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

完成创建源代码和bean和数据库连接信息的文件配置后,运行应用程序。这里先简单说明一下运行的步骤,在项目名称(StoredProcedure)上点击右键,在弹出的菜单中选择:【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
----Listing Record with ID = 1 -----
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