本文參考博客https://my.oschina.net/kailuncen/blog/905395,後本身驗證的。mysql
最重要的參數,以下List-1:sql
List-1bash
useServerPrepStmts=true&&cachePrepStmts=true
首先來看不加List-1參數的狀況,以下List-2:服務器
List-2session
url=jdbc:mysql://127.0.0.1:3306/mjduan?useUnicode=true&characterEncoding=utf-8&useSSL=false
服務器端MySQL的general日誌裏面內容以下List-3:優化
List-3 執行的三條語句被打印出來了url
2018-06-12T23:37:54.142048Z 10 Query SET NAMES utf8 2018-06-12T23:37:54.143931Z 10 Query SET character_set_results = NULL 2018-06-12T23:37:54.145705Z 10 Query SET autocommit=1 2018-06-12T23:37:54.210026Z 10 Query SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:37:54.236635Z 10 Query SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:37:54.239985Z 10 Query SELECT id,name,age FROM student WHERE id = 1
JDBC鏈接的url中添加useServerPrepStmts=true,以下List-4:.net
List-4日誌
url=jdbc:mysql://127.0.0.1:3306/mjduan?useUnicode=true&characterEncoding=utf-8&useSSL=false&&useServerPrepStmts=true
下面的List-5中,每一個Ececute以前都有一個Prepare,說明執行SQL以前,都對該SQL進行解析、優化了,因此沒有起到預編譯的做用。code
List-5
2018-06-12T23:29:34.175252Z 5 Query SET NAMES utf8 2018-06-12T23:29:34.176954Z 5 Query SET character_set_results = NULL 2018-06-12T23:29:34.178768Z 5 Query SET autocommit=1 2018-06-12T23:29:34.214910Z 5 Prepare SELECT id,name,age FROM student WHERE id = ? 2018-06-12T23:29:34.244389Z 5 Execute SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:29:34.265083Z 5 Close stmt 2018-06-12T23:29:34.266680Z 5 Prepare INSERT INTO student(name,age) VALUES(?, ?) 2018-06-12T23:29:34.268304Z 5 Query select @@session.tx_read_only 2018-06-12T23:29:34.275772Z 5 Execute INSERT INTO student(name,age) VALUES('明明', 20) 2018-06-12T23:29:34.283289Z 5 Close stmt 2018-06-12T23:29:34.284142Z 5 Prepare SELECT id,name,age FROM student WHERE id = ? 2018-06-12T23:29:34.285013Z 5 Execute SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:29:34.287157Z 5 Close stmt
JDBC鏈接的url加上useServerPrepStmts=true&cachePrepStmts=true,以下List-6所示:
List-6
url=jdbc:mysql://127.0.0.1:3306/mjduan?useUnicode=true&characterEncoding=utf-8&useSSL=false&&useServerPrepStmts=true&cachePrepStmts=true
再去看MySQL的general日誌,如List-7,此次生效了。
List-7 執行三條同樣的語句,只有一次Prepare
2018-06-12T23:44:03.197228Z 11 Query SET NAMES utf8 2018-06-12T23:44:03.202524Z 11 Query SET character_set_results = NULL 2018-06-12T23:44:03.206439Z 11 Query SET autocommit=1 2018-06-12T23:44:03.310079Z 11 Prepare SELECT id,name,age FROM student WHERE id = ? 2018-06-12T23:44:03.378740Z 11 Execute SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:44:03.427651Z 11 Execute SELECT id,name,age FROM student WHERE id = 1 2018-06-12T23:44:03.431207Z 11 Execute SELECT id,name,age FROM student WHERE id = 1
注意:
預編譯功能只是在同一個Connection中生效,一個Connection沒法獲取另外一個Connection中的預編譯結果。
因此,使用Mybatis時,預編譯功能只在同一個SqlSession中生效?這種說明不對,倆個SqlSession有可能拿到的是同一個Connection(所以DataSource),這個時候這倆個SqlSession就能共享該Connection中的預編譯結果。
預編譯,其實有些人說預準備更恰當,不過如今幾本都說預編譯了。
參考: