通常咱們主要的JDBC處理流程以下:html
首先聲明:這個階段在1.6以後就不須要手動執行了,也就是這個代碼不須要了!!!分析它有利於理解流程。java
Class.forName("com.mysql.jdbc.Driver")
上面代碼發生在註冊Driver階段,指的是讓JVN將com.mysql.jdbc.Driver這個類加載入內存中,最重要的是將mysql驅動註冊到DriverManager中去。mysql
此處加載Driver
的時候,加載的是java.mysql.jdbc
包下的,這實際上是一種向後兼容的作法,實際上代碼都是寫在了com.mysql.cj.jdbc
下,因此,mysql的鏈接包使用了繼承的方式,com.mysql.jdbc.Driver
只是對外的一個兼容類,其父類是com.mysql.cj.jdbc.Driver
,真正的的mysql Driver驅動。sql
加載Driver
的目的就是加載它的父類:數據庫
public class Driver extends com.mysql.cj.jdbc.Driver { public Driver() throws SQLException { super(); }}
咱們打開com.mysql.cj.jdbc.Driver
,能夠發現,裏面有一個構造空方法,這也是調用Class.forName().newInstance()
所須要的,這個類繼承了NonRegisteringDriver
,實現了java.mysql.Driver
。
裏面有一個空無參構造方法,爲反射調用newInstance()
準備的,另外就是靜態代碼塊,靜態代碼塊主要的功能是經過DriverManager
註冊本身(Driver
,也就是驅動),這裏很重要的一點,就是Driver是java.sql.Driver
(這是jdk的包!!!)的實現。數據結構
咱們引入的驅動本質上是JDK中的Driver的實現類,爲啥?這就是標準,約束,不這樣幹,不合規矩。併發
public class Driver extends NonRegisteringDriver implements java.sql.Driver { static { try { // 調用DriverManager 註冊本身(Driver) java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } public Driver() throws SQLException { // Class.forName().newInstance() 所須要的 }}
DriverManager
裏面基本全是static方法,也就是專門管理各類驅動的,registerDriver()
方法如同其名字,就是爲了註冊驅動,註冊到哪裏呢?
看下面的代碼,能夠知道,driverInfo(驅動相關信息)會被添加到registeredDrivers
裏面去。registeredDrivers
是DriverManager的static屬性,裏面存放着註冊的驅動信息。若是這個驅動已經被註冊,那麼就不會再註冊。app
public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException { registerDriver(driver, null); } public static synchronized void registerDriver(java.sql.Driver driver, DriverAction da) throws SQLException { /* Register the driver if it has not already been added to our list */ if(driver != null) { // 將驅動相關信息加到registeredDrivers registeredDrivers.addIfAbsent(new DriverInfo(driver, da)); } else { // This is for compatibility with the original DriverManager throw new NullPointerException(); } println("registerDriver: " + driver); }
到這裏其實Class.forName(「com.mysql.jdbc.Driver」)
這句代碼分析就結束了。jvm
類加載,是將類的.class文件(二進制數據)翻譯讀進內存中,放在虛擬機的運行時數據區裏面的方法區內。對應的在堆裏面建立一個java.lang.Class
對象,java裏面萬物皆對象,類本質也是對象,這個建立的對象就是封裝了類自己在方法區的數據結構,這纔是類加載的目的。
再簡單一點,就是將類的信息,弄成一個Class對象,放到堆上面,其數據結構在方法區,堆上面的對象是一種封裝。ide
類加載有三種方式,後面兩種是反射的時候使用居多。
Class.forName()
手動加載ClassLoader.loadClass()
手動加載爲何使用Class.forName()
而不是ClassLoader.loadClass()
,必定要這樣作麼?二者有什麼區別?(先埋一個坑)先簡單解釋一下:
Class.forName()
除了將類的.Class
文件加載到JVM中以外,還會對類進行解釋,執行類的static代碼塊,也就是默認會初始化類的一些數據(能夠設置爲不執行)。可是classLoader
是沒有的,classLoader
只有在newInstance()
的時候纔會執行static塊。
而咱們上面看到的com.mysql.cj.jdbc.Driver
這個類就是使用static的方式將本身註冊到DriverManager
中,因此須要使用Class.forName()
。
Class.forName(xxx.xx.xx).newInstance()
可不能夠,能夠,可是沒有必要。這樣至關於順帶建立出了實例。咱們只是須要知足在JDBC規範中明確要求這個Driver類必須向DriverManager註冊本身
這個條件,而觸發其中的靜態代碼塊便可。
we just want to load the driver to jvm only, but not need to user the instance of driver,
so call Class.forName(xxx.xx.xx) is enough, if you call Class.forName(xxx.xx.xx).newInstance(),
the result will same as calling Class.forName(xxx.xx.xx),
because Class.forName(xxx.xx.xx).newInstance() will load driver first,
and then create instance, but the instacne you will never use in usual,
so you need not to create it.
Class.forName()
代碼以下,能夠看到的是,調用forName(String name, boolean initialize,ClassLoader loader, Class
,傳入的是一個true,也就是會初始化。
@CallerSensitive public static Class<?> forName(String className) throws ClassNotFoundException { Class<?> caller = Reflection.getCallerClass(); return forName0(className, true, ClassLoader.getClassLoader(caller), caller); }
咱們將Class.forName()
註釋掉,個人mysql-connector版本是8.0以上,JDK是1.8,仍是能夠運行的以下:
這是什麼緣由呢???
仔細一點就會發現,在咱們引入的mysql
包中,有一個配置文件,java.sql.Driver
,裏面配置了
這裏使用了SPI
的技術,也就是Service provider Interface
機制,JDK 容許第三方產商或者插件,對JDK的規範作不同的定製或者拓展。JVM在啓動的時候能夠檢測到接口的實現,若是配置了的驅動就會自動由DriverManager
加載註冊。這就是爲何不須要顯式調用的緣由。
也就是JDK定義好接口和規範,引入的包去實現它,而且把實現的全限定類名配置在指定的地方(META-INF文件目錄中),代表須要加載這個接口,那麼JVM就會一塊兒加載它。具體的源碼是ServiceLoader
下面的load()
方法。
public static <S> ServiceLoader<S> load(Class<S> service) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return ServiceLoader.load(service, cl); }
加載完成了驅動,咱們須要獲取和數據庫的鏈接,鏈接數據庫咱們都知道是須要數據庫地址,用戶名,和密碼。
connection=DriverManager.getConnection(URL,USER,PASSWROD);
二話不說,看內部實現。裏面實際上是用用戶和密碼構造了一個Properties對象,而後傳到另外一個方法中進行調用。
public static Connection getConnection(String url, String user, String password) throws SQLException { java.util.Properties info = new java.util.Properties(); if (user != null) { info.put("user", user); } if (password != null) { info.put("password", password); } return (getConnection(url, info, Reflection.getCallerClass())); }
真正獲取連接的代碼以下,獲取真正的類加載器,和當前driver的加載器對比,
private static Connection getConnection( String url, java.util.Properties info, Class<?> caller) throws SQLException { /* * When callerCl is null, we should check the application's * (which is invoking this class indirectly) * classloader, so that the JDBC driver class outside rt.jar * can be loaded from here. */ ClassLoader callerCL = caller != null ? caller.getClassLoader() : null; synchronized(DriverManager.class) { // synchronize loading of the correct classloader. if (callerCL == null) { callerCL = Thread.currentThread().getContextClassLoader(); } } if(url == null) { throw new SQLException("The url cannot be null", "08001"); } println("DriverManager.getConnection(\"" + url + "\")"); // Walk through the loaded registeredDrivers attempting to make a connection. // Remember the first exception that gets raised so we can reraise it. SQLException reason = null; for(DriverInfo aDriver : registeredDrivers) { // If the caller does not have permission to load the driver then // skip it. if(isDriverAllowed(aDriver.driver, callerCL)) { try { println(" trying " + aDriver.driver.getClass().getName()); Connection con = aDriver.driver.connect(url, info); if (con != null) { // Success! println("getConnection returning " + aDriver.driver.getClass().getName()); return (con); } } catch (SQLException ex) { if (reason == null) { reason = ex; } } } else { println(" skipping: " + aDriver.getClass().getName()); } } if (reason != null) { println("getConnection failed: " + reason); throw reason; } println("getConnection: no suitable driver found for "+ url); throw new SQLException("No suitable driver found for "+ url, "08001"); }
爲何要這樣設計?Reflection.getCallerClass()
是反射中的方法,他的做用是獲取它的調用類,也就是哪個類調用了這個方法,之前這個方法是Reflection.getCallerClass(int n)
,也就是支持傳入一個n,返回調用棧的第n幀的類,好比A調用了B,B調用Reflection.getCallerClass(2)
,當前的Reflection類位於調用棧的第0幀,B位於第1幀,A就是第二幀。
改爲無參數的Reflection.getCallerClass()
方法以後,Reflection.getCallerClass()
方法調用所在的方法必須用@CallerSensitive
進行註解,g該方法獲取class時會跳過調用鏈路上全部的有@CallerSensitive
註解的方法的類,直到遇到第一個未使用該註解的類,返回。咱們能夠知道,源碼中的全部的getConnection()
都是有註解的,證實會返回咱們真正的調用的類。
提及 JDBC
的時候,咱們自定義一下的數據庫鏈接工具:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DBUtil { private static String URL="jdbc:mysql://127.0.0.1:3306/test"; private static String USER="root"; private static String PASSWROD ="123456"; private static Connection connection=null; static{ try { Class.forName("com.mysql.jdbc.Driver"); // 獲取數據庫鏈接 connection=DriverManager.getConnection(URL,USER,PASSWROD); System.out.println("鏈接成功"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 返回數據庫鏈接 public static Connection getConnection(){ return connection; }}
上面的作法,是一直使用同一個connection
,這樣在併發的時候仍是頗有缺陷的,因此咱們須要多個線程同時操做不一樣的connection
,可是一直建立connection
是須要較大的開銷的,那這樣應該怎麼作呢?這就不得不說到鏈接池技術了。
數據庫鏈接池,就是負責分配,管理和釋放數據庫鏈接,使用完以後的鏈接,放回到數據庫鏈接池中,能夠重複利用。
此文章僅表明本身(本菜鳥)學習積累記錄,或者學習筆記,若有侵權,請聯繫做者刪除。人無完人,文章也同樣,文筆稚嫩,在下不才,勿噴,若是有錯誤之處,還望指出,感激涕零~
技術之路不在一時,山高水長,縱使緩慢,馳而不息。
公衆號:秦懷雜貨店