一、首先介紹一下官方Jdbc的基本功能
JdbcTemplate基本使用
- execute方法
- update與batchUpdate方法
- query與queryXXX方法
- call方法
二、需要注意哪些細節
1、如何獲取數據庫連接。
2、如何管理連接。
3、如何保證不同的線程使用的不是同一個連接,不能讓其它線程干擾到本線程的執行。
4、保證同一個線程使用的是同一個連接,不能把b線程的數據提交到a線程上面去了。
4、異常處理,提交和回滾。
三、源碼實現
1、實現事物管理器
package com.biubiu.transaction;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author yule.zhang
* @date 2019/9/29 23:01
* @email [email protected]
* @description 事物管理器
*/
@Component
public class MyTransactionManager {
@Resource
private DataSource dataSource;
//保證不同的線程使用的是不同的連接,同一個線程使用同一個連接
ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
Connection connection = null;
public Connection getConnection() throws SQLException {
connection = threadLocal.get();
if(connection != null) {
return connection;
} else {
connection = dataSource.getConnection();
threadLocal.set(connection);
}
return connection;
}
}
2、實現JdbcTemplate的封裝
package com.biubiu.transaction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author yule.zhang
* @date 2019/9/29 22:53
* @email [email protected]
* @description JdbcTemplate
*/
@Component
public class MyJdbcTemplate {
@Resource
private MyTransactionManager myTransactionManager;
public void execute(String sql) {
Connection connection = null;
Statement stmt = null;
try{
connection = myTransactionManager.getConnection();
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.execute(sql);
connection.commit();
}catch(Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
四、最後再推薦一個編程方向的公衆號,您的專注是我創作的最大動力。
號主爲一線大廠架構師,博客訪問量突破一千萬。主要分享Java、golang架構,源碼,分佈式,高併發等技術,用大廠程序員的視角來探討技術進階、面試指南、職業規劃等。15W技術人的選擇!