傳統 JDBC 回顧 JDBC 我們一定不陌生,剛開始學習的時候,我們寫過很多很多重覆的模板代碼: 現在光是看著就頭大,並且我還把它完整的寫了出來..真噁心! 這還僅僅是一個 JDBC 的方法,並且最主要的代碼只有 這麼一句,而且有很多模板化的代碼,包括建立連接以及關閉連接..我們必須想辦法解決一下 ...
傳統 JDBC 回顧
JDBC 我們一定不陌生,剛開始學習的時候,我們寫過很多很多重覆的模板代碼:
public Student getOne(int id) {
String sql = "SELECT id,name FROM student WHERE id = ?";
Student student = null;
// 聲明 JDBC 變數
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 註冊驅動程式
Class.forName("com.myql.jdbc.Driver");
// 獲取連接
con = DriverManager.getConnection("jdbc://mysql://localhost:" +
"3306/student", "root", "root");
// 預編譯SQL
ps = con.prepareStatement(sql);
// 設置參數
ps.setInt(1, id);
// 執行SQL
rs = ps.executeQuery();
// 組裝結果集返回 POJO
if (rs.next()) {
student = new Student();
student.setId(rs.getInt(1));
student.setName(rs.getString(1));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// 關閉資料庫連接資源
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null && con.isClosed()) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return student;
}
現在光是看著就頭大,並且我還把它完整的寫了出來..真噁心!
這還僅僅是一個 JDBC 的方法,並且最主要的代碼只有ps = con.prepareStatement(sql);
這麼一句,而且有很多模板化的代碼,包括建立連接以及關閉連接..我們必須想辦法解決一下!
優化傳統的 JDBC
第一步:創建 DBUtil 類
我想第一步我們可以把重覆的模板代碼提出來創建一個【DBUtil】資料庫工具類:
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
static String ip = "127.0.0.1";
static int port = 3306;
static String database = "student";
static String encoding = "UTF-8";
static String loginName = "root";
static String password = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
return DriverManager.getConnection(url, loginName, password);
}
}
這樣我們就可以把上面的噁心的代碼變成這樣:
public Student getOne(int id) {
String sql = "SELECT id,name FROM student WHERE id = ?";
Student student = null;
// 聲明 JDBC 變數
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 獲取連接
con = DBUtil.getConnection();
// 預編譯SQL
ps = con.prepareStatement(sql);
// 設置參數
ps.setInt(1, id);
// 執行SQL
rs = ps.executeQuery();
// 組裝結果集返回 POJO
....
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉資料庫連接資源
....
}
return student;
}
也只是少寫了一句註冊驅動程式少處理了一個異常而已,並沒有什麼大的變化,必須再優化一下
第二步:使用 try-catch 語句自動關閉資源
自動資源關閉是 JDK 7 中新引入的特性,不瞭解的同學可以去看一下我之前寫的文章:JDK 7 新特性
於是代碼可以進一步優化成這樣:
public Student getOne(int id) {
String sql = "SELECT id,name FROM student WHERE id = ?";
Student student = null;
// 將 JDBC 聲明變數包含在 try(..) 里將自動關閉資源
try (Connection con = DBUtil.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) {
// 設置參數
ps.setInt(1, id);
// 執行SQL
ResultSet rs = ps.executeQuery();
// 組裝結果集返回 POJO
if (rs.next()) {
student = new Student();
student.setId(rs.getInt(1));
student.setName(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
這樣看著好太多了,但仍然不太滿意,因為我們最核心的代碼也就只是執行 SQL 語句並拿到返回集,再來再來
再進一步改進 DBUtil 類:
在 DBUtil 類中新增一個方法,用來直接返回結果集:
public static ResultSet getResultSet(String sql, Object[] objects) throws SQLException {
ResultSet rs = null;
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(sql)) {
// 根據傳遞進來的參數,設置 SQL 占位符的值
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
// 執行 SQL 語句並接受結果集
rs = ps.executeQuery();
}
// 返回結果集
return rs;
}
這樣我們就可以把我們最開始的代碼優化成這樣了:
public Student getOne(int id) {
String sql = "SELECT id,name FROM student WHERE id = ?";
Object[] objects = {id};
Student student = null;
try (ResultSet rs = DBUtil.getResultSet(sql, objects);) {
student.setId(rs.getInt(1));
student.setName(rs.getString(1));
} catch (SQLException e) {
// 處理異常
e.printStackTrace();
}
return student;
}
wooh!看著爽多了,但美中不足的就是沒有把 try-catch 語句去掉,我們也可以不進行異常處理直接把 SQLException 拋出去:
public Student getOne(int id) throws SQLException {
String sql = "SELECT id,name FROM student WHERE id = ?";
Object[] objects = {id};
Student student = null;
try (ResultSet rs = DBUtil.getResultSet(sql, objects);) {
student.setId(rs.getInt(1));
student.setName(rs.getString(1));
}
return student;
}
其實上面的版本已經夠好了,這樣做只是有些強迫症。
- 我們自己定義的 DBUtil 工具已經很實用了,因為是從模板化的代碼中抽離出來的,所以我們可以一直使用
Spring 中的 JDBC
要想使用 Spring 中的 JDBC 模塊,就必須引入相應的 jar 文件:
- 需要引入的 jar 包:
- spring-jdbc-4.3.16.RELEASE.jar
- spring-tx-4.3.16.RELEASE.jar
好在 IDEA 在創建 Spring 項目的時候已經為我們自動部署好了,接下來我們來實際在 Spring 中使用一下 JDBC:
配置資料庫資源
就像我們創建 DBUtil 類,將其中連接的信息封裝在裡面一樣,我們需要將這些資料庫資源配置起來
- 配置方式:
- 使用簡單資料庫配置
- 使用第三方資料庫連接池
我們可以使用 Spring 內置的類來配置,但大部分時候我們都會使用第三方資料庫連接池來進行配置,由於使用第三方的類,一般採用 XML 文件配置的方式,我們這裡也使用 XML 文件配置的形式:
使用簡單資料庫配置
首先我們來試試 Spring 的內置類 org.springframework.jdbc.datasource.SimpleDriverDataSource
:
<bean id="dateSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc://mysql://locolhost:3306/student"/>
</bean>
我們來測試一下,先把我們的 JDBC 操作類寫成這個樣子:
package jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pojo.Student;
import javax.sql.DataSource;
import java.sql.*;
@Component("jdbc")
public class JDBCtest {
@Autowired
private DataSource dataSource;
public Student getOne(int stuID) throws SQLException {
String sql = "SELECT id, name FROM student WHERE id = " + stuID;
Student student = new Student();
Connection con = dataSource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
}
return student;
}
}
然後編寫測試類:
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
JDBCtest jdbc = (JDBCtest) context.getBean("jdbc");
Student student = jdbc.getOne(123456789);
System.out.println(student.getId());
System.out.println(student.getName());
成功取出資料庫中的數據:
使用第三方資料庫連接池
上面配置的這個簡單的數據源一般用於測試,因為它不是一個資料庫連接池,知識一個很簡單的資料庫連接的應用。在更多的時候,我們需要使用第三方的資料庫連接,比如使用 C3P0資料庫連接池:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="10"></property>
<property name="maxStatements" value="100"></property>
<property name="acquireIncrement" value="2"></property>
</bean>
跟上面的測試差不多,不同的是需要引入相關支持 C3P0 資料庫連接池的 jar 包而已。
Jdbc Template
Spring 中提供了一個 Jdbc Template 類,它自己已經封裝了一個 DataSource 類型的變數,我們可以直接使用:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSrouce" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student"/>
</bean>
<context:component-scan base-package="jdbc" />
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSrouce"/>
</bean>
</beans>
我們來改寫一下 JDBC 操作的類:
package jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import pojo.Student;
import java.sql.*;
@Component("jdbc")
public class JDBCtest {
@Autowired
private JdbcTemplate jdbcTemplate;
public Student getOne(int stuID) throws SQLException {
String sql = "SELECT id, name FROM student WHERE id = ?";
Student student = jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
return stu;
}
}, 123456789);
return student;
}
}
測試類不變,運行可以獲得正確的結果:
但是好像並沒有簡單多少的樣子,那我們來看看其他 CRUD 的例子:
/**
* 增加一條數據
*
* @param student
*/
public void add(Student student) {
this.jdbcTemplate.update("INSERT INTO student(id,name) VALUES(?,?)",
student.getId(), student.getName());
}
/**
* 更新一條數據
*
* @param student
*/
public void update(Student student) {
this.jdbcTemplate.update("UPDATE student SET name = ? WHERE id = ?",
student.getName(), student.getId());
}
/**
* 刪除一條數據
*
* @param id
*/
public void delete(int id) {
this.jdbcTemplate.update("DELETE FROM student WHERE id = ?",
id);
}
現在應該簡單多了吧,返回集合的話只需要稍微改寫一下上面的 getOne() 方法就可以了
擴展閱讀:官方文檔 、 Spring 中 JdbcTemplate 實現增刪改查
參考資料:
- 《Java EE 互聯網輕量級框架整合開發》
- 《Spring 實戰》
- 全能的百度和萬能的大腦
擴展閱讀:① 徹底理解資料庫事務、② Spring事務管理詳解、③ Spring 事務管理(詳解+實例)、④ 全面分析 Spring 的編程式事務管理及聲明式事務管理
歡迎轉載,轉載請註明出處!
@我沒有三顆心臟
CSDN博客:http://blog.csdn.net/qq939419061
簡書:http://www.jianshu.com/u/a40d61a49221