Spring 中 SQL 的存储过程
SimpleJdbcCall 类可以被用于调用一个包含 IN 和 OUT 参数的存储过程。你可以在处理任何一个 RDBMS 时使用这个方法,就像 Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle,和 Sybase。
为了了解这个方法,我们使用我们的 Student 表,它可以在 MySQL TEST 数据库中使用下面的 DDL 进行创建:
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
下一步,考虑接下来的 MySQL 存储过程,该过程使用 学生 Id 并且使用 OUT 参数返回相应的学生的姓名和年龄。所以让我们在你的 TEST 数据库中使用 MySQL 命令提示符创建这个存储过程:
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 ;
现在,让我们编写我们的 Spring JDBC 应用程序,它可以实现对我们的 Student 数据库表的创建和读取操作。让我们使 Eclipse IDE 处于工作状态,然后按照如下步骤创建一个 Spring 应用程序:
| 步骤 | |
|---|---|
| 1 | 创建一个名为 SpringExample 的项目,并且在所创建项目的 src 文件夹下创建一个名为 com.cnblogs 的包。 | 
| 2 | 使用 Add External JARs 选项添加所需的 Spring 库文件. | 
| 3 | 在项目中添加 Spring JDBC 指定的最新的库文件 mysql-connector-java.jar, org.springframework.jdbc.jar 和 org.springframework.transaction.jar。如果你还没有这些所需要的库文件,你可以下载它们。 | 
| 4 | 创建 DAO 接口 StudentDAO 并且列出所有需要的方法。 即使他不是必需的,你可以直接编写 StudentJDBCTemplate 类,但是作为一个良好的实践,让我们编写它。 | 
| 5 | 在 com.cnblogs 包下创建其他所需要的 Java 类 Student, StudentMapper, StudentJDBCTemplate 和 MainApp。 | 
| 6 | 确保你已经在 TEST 数据库中创建了 Student 表。同样确保你的 MySQL 服务器是正常工作的,并且保证你可以使用给定的用户名和密码对数据库有读取/写入的权限。 | 
| 7 | 在 src 文件夹下创建 Beans 配置文件 Beans.xml。 | 
| 8 | 最后一步是创建所有 Java 文件和 Bean 配置文件的内容,并且按如下解释的那样运行应用程序。 | 
下面是数据访问对象接口文件 StudentDAO.java 的内容:
package com.cnblogs;
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
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
}
下面是 Student.java 文件的内容:
package com.cnblogs;
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.cnblogs;
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:
package com.cnblogs;
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; public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private SimpleJdbcCall jdbcCall;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcCall = new SimpleJdbcCall(dataSource).
withProcedureName("getRecord");
}
public void create(String name, Integer age) {
JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public Student getStudent(Integer id) {
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;
}
public List<Student> listStudents() {
JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL,new StudentMapper());
return students;
}
}
关于上述项目的几句话:你编写的课调用执行的代码涉及创建一个包含 IN 参数的 SqlParameterSource。名称的匹配是很重要的,该名称可以使用在存储过程汇总声明的参数名称来提供输入值。execute 方法利用 IN 参数返回一个包含在存储过程中由名称指定的任何外部参数键的映射。现在让我们移动主应用程序文件 MainApp.java,如下所示:
package com.cnblogs;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cnblogs.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);
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());
}
System.out.println("----Listing Record with ID = 2 -----" );
Student student = studentJDBCTemplate.getStudent(2);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge());
}
}
下面是配置文件 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"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean> <!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate"
class="com.cnblogs.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean> </beans>
一旦你已经完成的创建了源文件和 bean 配置文件,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 2
 Spring 中 SQL 的存储过程的更多相关文章
- SqlServer中Sql查看存储过程
		( 一)利用Sql语句查询数据库中的所有表 1.利用sysobjects系统表 select * from sysobjects where xtype='U' 2,利用sys.tables目录视图 ... 
- SQL Server 在多个数据库中创建同一个存储过程(Create Same Stored Procedure in All Databases)
		一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 遇到的问题(Problems) 实现代码(SQL Codes) 方法一:拼接SQL: 方法二: ... 
- SQL Server存储过程中使用表值作为输入参数示例
		这篇文章主要介绍了SQL Server存储过程中使用表值作为输入参数示例,使用表值参数,可以不必创建临时表或许多参数,即可向 Transact-SQL 语句或例程(如存储过程或函数)发送多行数据,这样 ... 
- sql 解析字符串添加到临时表中 sql存储过程in 参数输入
		sql 解析字符串添加到临时表中 sql存储过程in 参数输入 解决方法 把字符串解析 添加到 临时表中 SELECT * into #临时表 FROM dbo.Func_SplitOneCol ... 
- Spring 中jdbcTemplate 实现执行多条sql语句
		说一下Spring框架中使用jdbcTemplate实现多条sql语句的执行: 很多情况下我们需要处理一件事情的时候需要对多个表执行多个sql语句,比如淘宝下单时,我们确认付款时要对自己银行账户的表里 ... 
- Sql Server 存储过程中查询数据无法使用 Union(All)
		原文:Sql Server 存储过程中查询数据无法使用 Union(All) 微软Sql Server数据库中,书写存储过程时,关于查询数据,无法使用Union(All)关联多个查询. 1.先看一段正 ... 
- 在PL/SQL中调用Oracle存储过程
		存储过程 1 什么是存储过程? 用于在数据库中完成特定的操作或者任务.是一个PLSQL程序块,可以永久的保存在数据库中以供其他程序调用. 2 存储过程的参数模式 存储过程的参数特性: IN类型的参数 ... 
- 在Spring中配置SQL server 2000
		前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ... 
- C# 调用存储过程 Sql Server存储过程 存储过程报错,程序中的try
		C#程序调用Sql Server存储过程,存储过程中报错情况,返回值... 0.SQL存储过程 USE [Opos] GO /****** Object: StoredProcedure [dbo]. ... 
随机推荐
- C#代码总结04---通过创建临时表DataTable进行临时编辑删除
			<script type="text/javascript"> //删除 function Delete(hdGuid) { $("#hdGuid" ... 
- iOS 轻击、触摸和手势的检测
			一.检测捏合手势( UIPinchGestureRecognizer): //设定一个实例变量存储手指之间的其起始距离 @property (assign, nonatomic) CGFloat i ... 
- 【C语言编程练习】5.9 爱因斯坦的阶梯问题
			1. 题目要求 有一个长阶梯,每2步上,最后剩1个台阶,若每3步上,最后剩2个台阶.若每5步上,最后剩4个台阶,若每6步上,最后剩5个台阶.只有每步上7阶,才可以刚好走完,请问台阶至少有多少阶? 2. ... 
- MongoDB 用Robomong可视化工具操作的 一些简单语句
			一.数据更新 db.getCollection('表名').update({ "字段":{$in:["值"]} }, //更新条件 {$set:{ " ... 
- .NET题目(收集来自网络)
			1: .NET和c#有什么区别? 答: .NET一般是指.NET FrameWork框架,是一种平台,一种技术 c#是一种编程语言,是可以基于.NET平台的应用 2: c#中的委托是什么?事件是不是一 ... 
- Vue(MVVM)、React(MVVM)、Angular(MVC)对比
			前言 昨天阿里内推电面一面,面试官了解到项目中用过Vue,就问为什么前端框架使用Vue而不适用其他的框架,当时就懵了.因为只用过Vue,不了解其他两个框架,今天就赶紧去了解一下他们之间的区别.大家发现 ... 
- layui select使用问题
			1.需要引用form模板 layui.use(['form'], function () { var form = layui.form; }); 2.html代码 <div class=&qu ... 
- centos7 64运行32位程序
			yum在线安装: sudo yum install xulrunner.i686 或者: sudo yum install ia32-libs.i686 PS:可以查看一下当前源库里有没有ia32-l ... 
- js拼接字符串后swiper不能动的解决方案
			swiper的配置一定要放在拼接字符串之后,紧随其后,如果放在其他的位置,swiper是不识别HTML的. 
- aarch64的架构:unrecognized command line option '-mfpu=neon'
			不用添加这个'-mfpu=neon'的编译器选项了,因为这个架构下neon是默认启动的. 参考: https://lists.linaro.org/pipermail/linaro-toolchain ... 
