Spring入門學習筆記(4)——JDBC的使用
目錄
Spring JDBC框架概覽
使用傳統的JDBC連線資料庫,需要編寫不必要的程式碼來處理異常、開啟和關閉資料庫連線等變得非常麻煩。然而,Spring JDBC Framework從開啟連線、準備和執行SQL語句、處理異常、處理事務以及最後關閉連線開始,負責所有低級別的細節。
因此,您需要做的就是定義連線引數並指定要執行的SQL語句,並在從資料庫獲取資料的同時為每個迭代執行所需的工作。
Spring JDBC提供了幾種方法和相應不同的類來與資料庫進行介面。我將採用經典且最流行的方法來使用框架的JdbcTemplate類。這是管理所有資料庫通訊和異常處理的中心框架類。
JdbcTemplate類
JDBC模板類執行SQL查詢、更新語句、儲存過程呼叫、對結果集執行迭代,並提取返回的引數值。它還捕獲JDBC異常,並將其轉換為org.springframework.dao中定義的通用的、資訊更豐富的包。
一旦配置好,JdbcTemplate類的例項就是執行緒安全的。因此,您可以配置JdbcTemplate的一個例項,然後將這個共享引用安全地注入多個DAOs。
在使用JDBC模板類時,一個常見的做法是在Spring配置檔案中配置一個數據源,然後將這個共享資料來源bean注入到DAO類中,然後在資料來源的setter中建立JdbcTemplate。
配置資料來源
讓我們在資料庫測試中建立一個數據庫表Student。我們假設您正在使用MySQL資料庫,如果您使用任何其他資料庫,那麼您可以相應地更改DDL和SQL查詢。
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
現在需要為JDBC模板提供一個DataSource,以便它可以進行配置獲取資料庫許可權:
<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>
資料訪問物件(Data Access Object,DAO)
DAO表示資料訪問物件,通常用於資料庫互動。DAOs的存在是為了提供一種向資料庫讀寫資料的方法,它們應該通過應用程式的其他部分訪問它們的介面來公開此功能。
Spring中的DAO支援使得以一致的方式使用JDBC、Hibernate、JPA或JDO等資料訪問技術變得很容易。
執行SQL命令
讓我們看看如何使用SQL和JDBCTemplate物件對資料庫表執行CRUD(建立、讀取、更新和刪除)操作。
org.springframework.jdbc.core.JdbcTemplate是JDBC核心包中的中心類。它簡化了JDBC的使用,有助於避免常見錯誤。它執行核心JDBC工作流,讓應用程式程式碼提供SQL並提取結果。這個類執行SQL查詢或更新,在resultset上發起迭代,捕獲JDBC異常,並將它們轉換為org.springframework.dao中定義的更通用的、更有用的異常。
注:JdbcTemplate是執行緒安全的,關於執行緒安全,將會在後續的文章中加以介紹。
下面介紹使用到的方法,完整資訊見Spring JdbcTemplate API Reference
Example
以下專案我使用Maven進行構建,建立Maven專案,更新pom.xml檔案為以下內容
<?xml version="1.0" encoding="UTF-8"?>
<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>top.ninwoo.spring</groupId>
<artifactId>build-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Spring依賴 -->
<!-- 1.Spring核心依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 2.Spring dao依賴 -->
<!-- spring-jdbc包括了一些如jdbcTemplate的工具類 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 3.Spring web依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 4.Spring test依賴:方便做單元測試和整合測試 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</project>
- StudentDAO.java : 定義Student資料介面
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();
/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/
public void delete(Integer id);
/**
* This is the method to be used to update
* a record into the Student table.
*/
public void update(Integer id, Integer age);
}
- Student.java : Student類
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 : 將資料庫條目對映到Student物件,關於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;
}
}
這是一個函式介面,因此可以用作lambda表示式或方法引用的賦值目標。
RowMapper必須實現mapRow方法來對映ResultSet中的每一行資料。這個方法不應該呼叫ResultSet上的next();它只應該對映當前行的值。
@Nullable
T mapRow(java.sql.ResultSet rs,
int rowNum)
throws java.sql.SQLException
Parameters:
rs - the ResultSet to map (pre-initialized for the current row)
rowNum - the number of the current row
Returns:
the result object for the current row (may be null)
Throws:
java.sql.SQLException - if a SQLException is encountered getting column values (that is, there's no need to catch SQLException)
- StudentJDBCTemplate.java : Student資料介面的具體實現
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
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) {
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL,
new Object[]{id}, new StudentMapper());
return student;
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
public void delete(Integer id) {
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
}
public void update(Integer id, Integer age){
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
return;
}
}
建構函式:
- JdbcTemplate()
- JdbcTemplate(javax.sql.DataSource dataSource)
update:
public int update(java.lang.String sql,
@Nullable
java.lang.Object... args)
throws DataAccessException
queryForObject
<T> T queryForObject(java.lang.String sql,
java.lang.Object[] args,
RowMapper<T> rowMapper)
throws DataAccessException
- MainApp.java : 主函式
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.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("----Updating Record with ID = 2 -----" );
studentJDBCTemplate.update(2, 20);
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.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
- 輸出
------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
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 20