同時與數據庫使用普通的舊JDBC的工作,它變得繁瑣寫不必要的代碼來處理異常,打開和關閉數據庫連接等,但Spring的JDBC框架需要的所有低層次細節從打開連接,準備和執行SQL語句,過程異常,處理事務,最后關閉連接。
所以,你所要做的只是定義連接參數,并指定要執行的SQL語句,并做必要的工作,在每次迭代時從數據庫中獲取數據。
Spring JDBC提供了一些方法和相應不同的類與數據庫進行交互。我要采取經典和最流行的做法,利用JdbcTemplateclass框架。這是管理的所有數據庫的通信和異常處理中心框架類。
JdbcTemplate 類
JdbcTemplate類執行SQL查詢,更新語句和存儲過程調用,在結果集和提取返回參數值進行迭代。它還捕捉JDBC的異常并將其轉換為通用的,信息更豐富,除了在org.springframework.dao包中定義的層次結構。
JdbcTemplate類的實例是一次配置的線程。所以,你可以配置一個JdbcTemplate的一個實例,然后安全地注入這種共享引用到多個DAO。
使用JdbcTemplate類時,通常的做法是配置一個DataSource在Spring配置文件,然后依賴關系注入該共享數據源豆到DAO類,JdbcTemplate或者是在setter數據源創建。
配置數據源
讓我們一起創造數據庫test數據庫表的 student 。假設使用MySQL數據庫,如果使用其他數據庫,那么可以相應地改變你的DDL和SQL查詢。
1
2
3
4
5
6
|
CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR (20) NOT NULL , AGE INT NOT NULL , PRIMARY KEY (ID) ); |
現在,我們需要提供一個數據源給JdbcTemplate類,因此它可以自行配置,以獲得數據庫訪問。您可以配置數據源的XML文件中有一段代碼,如下圖所示:
1
2
3
4
5
6
7
|
<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> |
數據訪問對象 (DAO)
DAO表示這是通常用于數據庫交互的數據訪問對象。 DAO的存在是為了提供讀取和寫入數據到數據庫中,他們應該通過該應用程序的其余部分將訪問它們的接口公開此功能的一種手段。
在Spring的數據訪問對象(DAO)的支持使得它很容易與如JDBC,Hibernate,JPA和JDO以一致的方式進行數據訪問技術。
執行SQL語句
讓我們來看看如何使用SQL和的JdbcTemplate對象數據庫中的表執行CRUD(創建,讀取,更新和刪除)操作。
查詢一個整數:
1
2
|
String SQL = "select count(*) from Student" ; int rowCount = jdbcTemplateObject.queryForInt( SQL ); |
查詢長整數:
1
2
|
String SQL = "select count(*) from Student" ; long rowCount = jdbcTemplateObject.queryForLong( SQL ); |
使用綁定變量的簡單查詢:
1
2
|
String SQL = "select age from Student where id = ?" ; int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{ 10 }); |
在查詢字符串:
1
2
|
String SQL = "select name from Student where id = ?" ; String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{ 10 }, String. class ); |
查詢并返回一個對象:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
String SQL = "select * from Student where id = ?" ; Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{ 10 }, new StudentMapper()); 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; } } |
查詢并返回多個對象:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
String SQL = "select * from Student" ; List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); 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; } } |
插入一行到表:
1
2
|
String SQL = "insert into Student (name, age) values (?, ?)" ; jdbcTemplateObject.update( SQL, new Object[]{ "Zara" , 11 } ); |
1
2
|
String SQL = "update Student set name = ? where id = ?" ; jdbcTemplateObject.update( SQL, new Object[]{ "Zara" , 10 } ); |
從表中刪除行:
1
2
|
String SQL = "delete Student where id = ?" ; jdbcTemplateObject.update( SQL, new Object[]{ 20 } ); |
執行DDL語句
您可以使用execute(...)方法的JdbcTemplate來執行任何SQL語句或DDL語句。下面是一個示例使用CREATE語句創建一個表:
1
2
3
4
5
6
7
|
String SQL = "CREATE TABLE Student( " + "ID INT NOT NULL AUTO_INCREMENT, " + "NAME VARCHAR(20) NOT NULL, " + "AGE INT NOT NULL, " + "PRIMARY KEY (ID));" jdbcTemplateObject.execute( SQL ); |
SQL存儲過程
SimpleJdbcCall的類可以用來調用帶有IN和OUT參數的存儲過程。你可以使用這種方法,而與任何喜歡的Apache Derby,DB2,MySQL和微軟SQL服務器,Oracle和Sybase RDBMS中的工作。
其次,考慮以下的MySQL存儲過程這需要學生證和用OUT參數對應的學生的姓名和年齡的回報。因此,讓我們使用MySQL命令提示符下在測試數據庫中創建該存儲過程:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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應用程序,將執行我們的學生桌簡單的創建和讀取操作。
來創建一個Spring應用程序:
以下是數據訪問對象接口文件StudentDAO.java的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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 * 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文件的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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文件的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
package com.yiibai; 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() { String SQL = "select * from Student" ; List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); return students; } } |
關于上面的程序幾句話:你寫的調用的執行代碼時,需要創建包含IN參數的一個SqlParameterSource。重要的是要配合提供與存儲過程中聲明的參數名的輸入值的名稱。 execute方法接收傳入的參數,并返回包含任何列在存儲過程中指定的名稱鍵入參數的映射?,F在讓我們修改主應用程序文件MainApp.java,這是如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package com.yiibai; 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( "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文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<? 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.yiibai.StudentJDBCTemplate" > < property name = "dataSource" ref = "dataSource" /> </ bean > </ beans > |
創建源代碼和bean配置文件完成后,讓我們運行應用程序。如果一切順利,這將打印以下信息:
1
2
3
4
5
6
7
8
9
10
|
------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 |