一、Mybatis 流程簡介
最近在看 Mybatis 的原始碼,大致了解整個框架流程后便手寫了一個特別簡單的SimpMybatis的小Demo,來鞏固這整個框架的學習,下圖是我所畫的框架大致執行流程:

??對上圖分析后得出結論:
- Mybatis 的組態檔分為兩種,且這兩個組態檔會被封裝到 Configuration 中
- 主組態檔(MybatisConfig.xml):配置 jdbc 等環境資訊,全域唯一;
- 映射檔案(xxxMapper.xml):配置多個 Sql ,可有多個,
- 通過 Mybatis 組態檔得到 SqlSessionFactory ;
- 通過 SqlSessionFactory 得到 SqlSession,它就相當于 Request 請求;
- SqlSession 呼叫底層的 Executor 執行器來操作資料庫,同時執行器有兩類實作
- 基本實作
- 帶有快取功能的實作
- 決議傳入的引數,對其進行封裝,執行并回傳結果;
以上就是我梳理的 Mybatis 大致流程,看似簡單,卻很精妙,
二、手寫簡化版 Mybatis 設計思路
2.1 簡化后的思路

2.2 讀取 XML 檔案,建立連接
從圖中可以看出,MyConfig 負責與人互動,待讀取xml后,將屬性和連接資料庫的操作封裝在 MyConfig 物件中供后面的組件呼叫,本專案將使用 dom4j 來讀取xml檔案,它具有性能優異和非常方便使用的特點,
2.3 創建SqlSession,搭建 Configuration 和 Executor 之間的橋梁
從流程圖中的箭頭可以看出,MySqlSession 的成員變數中必須得有 MyExecutorImpl 和 MyConfig 去集中做調配,一個Session僅擁有一個對應的資料庫連接,類似于一個前段請求Request,它負責直接呼叫對應 execute(sql) 來做 CRUD 操作,
2.4 創建 MyExecutor,封裝 JDBC 操作資料庫
MyExecutor 是一個執行器,負責SQL陳述句的生成和查詢快取的維護,也就是 Jdbc 的代碼將在這里完成,不過本文只實作了單表,查詢快取并未實作,
2.5 創建 MySqlSessionProxy,使用動態代理生成 Mapper 物件
只是希望對指定的介面生成一個物件,使得執行它的時候能運行一句 sql,而介面無法直接呼叫方法,所以這里使用動態代理生成物件,在執行時還是回到 MySqlSession 中呼叫查詢,最終由 MyExecutorImpl 做 JDBC查詢,這樣設計是為了單一職責,可擴展性更強,
三、實作自己的Mybatis
這次會將其打成 Jar 包,并將其匯入專案實作,做一個 Mybatis 的還原,
工程檔案及目錄:

3.1 匯入兩個所需 Jar 包:資料庫連接和XML決議
Maven 匯入如下:
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<!-- xml決議 -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
3.2 創建 MyConfig 類,對兩大 XML 組態檔進行決議,并建立連接
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:17
*/
public class MyConfig {
/**
* 啟動應用程式類加載器
*/
private static final ClassLoader loader = ClassLoader.getSystemClassLoader();
/**
* 資料庫建立連接
* @return 回傳資料庫連接物件
*
*/
public Connection build() {
// Mybatis主組態檔名
String resource = "mybatis-config.xml";
// 獲取檔案根節點
Element root = parseXML(resource);
// 獲取檔案對應的資訊
Map<String, String> jdbcMap = parseNodes(root);
try {
Class.forName(jdbcMap.get("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException("驅動器未找到,請重新檢查!");
}
Connection connect = null;
try {
connect = DriverManager.getConnection(jdbcMap.get("url"), jdbcMap.get("username"), jdbcMap.get("password"));
} catch (SQLException throwables) {
throw new RuntimeException("資料庫連接錯誤,請檢查路徑、用戶名、密碼是否輸入正確!");
}
return connect;
}
/**
* 決議資料庫組態檔
* @param resource 資料庫組態檔路徑
* @return 獲取到的檔案根節點
*/
public static Element parseXML(String resource) {
try {
// 回傳用于讀取指定資源的輸入流
InputStream stream = loader.getResourceAsStream(resource);
// 使用dom4j決議XML
SAXReader reader = new SAXReader();
// 使用SAX從給定流中讀取檔案
Document doc = reader.read(stream);
// 獲取檔案的根節點
return doc.getRootElement();
} catch (DocumentException e) {
throw new RuntimeException("決議 XML 時發生錯誤!" + resource);
}
}
/**
* 決議主xml檔案標簽節點
* @param node 組態檔根節點
* @return 回傳從組態檔中拿到的開啟資料庫對應值
*/
private Map<String, String> parseNodes(Element node) {
// 判斷根標簽名稱
if (!node.getName().equals("database")) {
throw new RuntimeException("資料庫組態檔根標簽名稱必須為【database】");
}
// 存放組態檔取得的值
Map<String, String> map = new HashMap<String, String>();
map.put("driverClassName", null);
map.put("url", null);
map.put("username", null);
map.put("password", null);
// 讀取property的屬性內容
for (Element item : node.elements()) {
// 獲取標簽中存放的值,并洗掉其前導和結尾的空格
String value = https://www.cnblogs.com/-Koos-/archive/2021/04/01/getValue(item);
// 獲取標簽中 name 的名稱
String name = item.attributeValue("name");
// 如果name或value為空則有對應值未輸入
if (name == null || "".equals(value)) {
throw new RuntimeException("[database]: <property> 中應該包含名稱和值");
}
switch (name) {
case "driverClassName" : map.put("driverClassName", value); break;
case "url" : map.put("url", value); break;
case "username" : map.put("username", value); break;
case "password" : map.put("password", value); break;
default: throw new RuntimeException("[database]: <property> 中有未知屬性");
}
}
return map;
}
/**
* 獲取property屬性中的值
* @param node 組態檔根節點
* @return 如果有value值,則讀取;沒有設定value,則讀取內容
*/
private static String getValue(Element node) {
return node.hasContent() ? node.getText().trim() : node.attributeValue("value").trim();
}
/**
*
* @param path
* @return
*/
@SuppressWarnings(value = "https://www.cnblogs.com/-Koos-/archive/2021/04/01/rawtypes")
public MappingBean readMapper(String path) {
MappingBean bean = new MappingBean();
try {
InputStream stream = loader.getResourceAsStream(path);
SAXReader reader = new SAXReader();
Document doc = reader.read(stream);
Element root = doc.getRootElement();
// 把mapper節點的nameSpace值存為介面名
bean.setInterfaceName(root.attributeValue("nameSpace").trim());
// 用來存盤方法的List
List<Mapping> list = new ArrayList<Mapping>();
//遍歷根節點下所有子節點
for(Iterator rootIter = root.elementIterator(); rootIter.hasNext();) {
// 存盤一條方法的資訊
Mapping fun = new Mapping();
Element e = (Element) rootIter.next();
String sqlType = e.getName().trim();
String funcName = e.attributeValue("id").trim();
String sql = e.getText().trim();
String resultType = e.attributeValue("resultType").trim();
fun.setSqlType(sqlType);
fun.setFuncName(funcName);
Object newInstance = null;
try {
newInstance = Class.forName(resultType).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e1) {
e1.printStackTrace();
}
fun.setResultType(newInstance);
fun.setSql(sql);
list.add(fun);
}
bean.setList(list);
} catch (DocumentException e) {
e.printStackTrace();
}
return bean;
}
/**
* 決議mapper映射xml檔案
* @param element mapper檔案路徑
* @return
*/
public MappingBean parseMapper(Element element) {
MappingBean bean = new MappingBean();
String namespace = element.attributeValue("namespace");
if (namespace == null) {
throw new RuntimeException("映射檔案namespace不存在");
}
bean.setInterfaceName(namespace);
List<Mapping> list = new ArrayList<>();
Iterator<Element> it = element.elementIterator();
while (it.hasNext()) {
Element ele=(Element) it.next();
Mapping mapping =new Mapping();
String funcName =ele.attributeValue("id");
if (funcName==null){
throw new RuntimeException("mapper映射檔案中id不存在");
}
String sqlType = ele.getName();
String paramType = ele.attributeValue("parameterType");
String resultType=ele.attributeValue("resultType");
String sql=ele.getText().trim();
mapping.setFuncName(funcName);
mapping.setSqlType(sqlType);
mapping.setParameterType(paramType);
mapping.setSql(sql);
Object object=null;
try {
object=Class.forName(resultType).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
mapping.setResultType(object);
list.add(mapping);
}
bean.setList(list);
return bean;
}
}
?由 MyConfig類 代碼可以得知:
- Mybatis 主配置類名稱必須為:
mybatis-config.xml; - mybatis-config.xml 的根標簽必須為:
<database></database>; - Mapper.xml 必須包括:
namespace; - Sql 是否有回傳值都應包括:
resultType(個人偷懶,沒做判斷); - ... ...
3.3 MySqlSession 代理
MySqlSession 肯定不會自己去執行,因為不能寫死所以使用動態代理來使代理類去實作具體方法,
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:52
*/
public class MySqlSession {
private final MyExcutor excutor= new MyExcutorImpl();
private final MyConfig config = new MyConfig();
public <T> T selectValue(Mapping statement, List<Object> parameter){
return excutor.queryValue(statement, parameter);
}
public <T> T selectNull(Mapping statement){
return excutor.queryNull(statement);
}
public int deleteValue(Mapping statement, List<Object> parameter) {
return excutor.deleteValue(statement, parameter);
}
public int updateValue(Mapping statement, List<Object> parameter) {
return excutor.updateValue(statement, parameter);
}
public int insertValue(Mapping mapping, List<Object> parameter) {
return excutor.insertValue(mapping, parameter);
}
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> clas){
//動態代理呼叫
return (T) Proxy.newProxyInstance(clas.getClassLoader(),new Class[]{clas},
new MySqlSessionProxy(config,this));
}
}
撰寫代理類,把mapper映射檔案決議進來
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:55
*/
public class MySqlSessionProxy implements InvocationHandler {
private MyConfig config;
private MySqlSession sqlSession;
public MySqlSessionProxy(MyConfig config, MySqlSession sqlSession) {
this.config = config;
this.sqlSession = sqlSession;
}
@Override
public Object invoke(Object proxy, Method method,Object[] args) {
String name = method.getDeclaringClass().getName();
String mapperName = name.substring(name.lastIndexOf(".")+1);
MappingBean bean=config.parseMapper(MyConfig.parseXML(mapperName+".xml"));
if (bean!=null && (bean.getList()!=null && bean.getList().size()>0)){
for (Mapping mapping : bean.getList()){
if (mapping.getFuncName().equals(method.getName())) {
// 判斷是否為查詢陳述句
if ("select".equals(mapping.getSqlType().toLowerCase())) {
System.out.println("執行查詢方法:" + mapping.getSql());
if (args!=null) {
System.out.println("引數:"+ Arrays.toString(args));
return sqlSession.selectValue(mapping, Arrays.asList(args));
} else {
System.out.println("引數:null");
return sqlSession.selectNull(mapping);
}
}
// 判斷是否為洗掉陳述句
if ("delete".equals(mapping.getSqlType().toLowerCase())){
System.out.println("執行查詢方法:"+mapping.getSql());
System.out.println("引數:"+ Arrays.toString(args));
return sqlSession.deleteValue(mapping, Arrays.asList(args));
}
// 判斷是否為更新陳述句
if ("update".equals(mapping.getSqlType().toLowerCase())) {
System.out.println("執行查詢方法:"+mapping.getSql());
System.out.println("引數:"+ Arrays.toString(args));
return sqlSession.updateValue(mapping, Arrays.asList(args));
}
// 判斷是否為插入陳述句
if ("insert".equals(mapping.getSqlType().toLowerCase())) {
System.out.println("執行查詢方法:" + mapping.getSql());
System.out.println("引數:" + Arrays.toString(args));
return sqlSession.insertValue(mapping, Arrays.asList(args));
}
}
}
}
return null;
}
}
?注意:通過上段代碼可知,映射檔案必須和介面名稱保持一致,
3.4 創建對應物體類和XML映射檔案Sql物體類
a. 介面物體類
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:38
*/
public class MappingBean {
/**
* 介面名
*/
private String interfaceName;
/**
* 介面下所有方法
*/
private List<Mapping> list;
// setter、getter略
}
b. 映射檔案中 Sql 的物體類
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:38
*/
public class Mapping {
private String sqlType;
private String funcName;
private String sql;
private Object resultType;
private String parameterType;
// setter、getter略
}
3.5 創建 MyExcutor 介面以及實作類
MyExcutor 介面
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:42
*/
public interface MyExcutor {
// 無參查詢
<T> T queryNull(Mapping mapping);
// 有參查詢
<T> T queryValue(Mapping mapping, List<Object> params);
// 洗掉
int deleteValue(Mapping mapping, List<Object> params);
// 更新
int updateValue(Mapping mapping, List<Object> params);
// 插入
int insertValue(Mapping mapping, List<Object> params);
}
MyExcutorImpl 實作類
這里通過反射將結果轉換成物件
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 12:42
*/
public class MyExcutorImpl implements MyExcutor {
private MyConfig config = new MyConfig();
@Override
public <T> T queryNull(Mapping mapping) {
Connection conn = config.build();
PreparedStatement preparedStatement;
ResultSet resultSet;
Object obj;
List<Object> list = new ArrayList<>();
try {
preparedStatement=conn.prepareStatement(mapping.getSql());
if (mapping.getResultType() == null){
throw new RuntimeException("回傳的映射結果不能為空!");
}
resultSet = preparedStatement.executeQuery();
int row = 0;
ResultSetMetaData rd = resultSet.getMetaData();
while (resultSet.next()){
obj=resultToObject(resultSet,mapping.getResultType());
row++;
list.add(obj);
}
System.out.println("記錄行數:"+row);
} catch (SQLException e) {
e.printStackTrace();
}
return (T) list;
}
@Override
public <T> T queryValue(Mapping mapping, List<Object> params) {
Connection conn = config.build();
PreparedStatement preparedStatement;
ResultSet resultSet;
Object obj;
List<Object> list = new ArrayList<>();
try {
preparedStatement=conn.prepareStatement(mapping.getSql());
for (int i=0; i<params.size(); i++) {
preparedStatement.setString(i+1, params.get(i).toString());
}
if (mapping.getResultType() == null){
throw new RuntimeException("回傳的映射結果不能為空!");
}
resultSet = preparedStatement.executeQuery();
int row = 0;
ResultSetMetaData rd = resultSet.getMetaData();
while (resultSet.next()){
obj=resultToObject(resultSet,mapping.getResultType());
row++;
list.add(obj);
}
System.out.println("記錄行數:"+row);
} catch (SQLException e) {
e.printStackTrace();
}
return (T) list;
}
@Override
public int deleteValue(Mapping mapping, List<Object> params) {
Connection conn = config.build();
int rows = 0;
PreparedStatement preparedStatement=null;
try {
preparedStatement = conn.prepareStatement(mapping.getSql());
for (int i=0; i<params.size(); i++) {
preparedStatement.setString(i+1, params.get(i).toString());
}
rows = preparedStatement.executeUpdate();
if (rows != 0) {
System.out.println("洗掉成功,受影響行數:"+rows);
} else {
System.out.println("洗掉失敗,資料庫無相應資料...");
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
@Override
public int updateValue(Mapping mapping, List<Object> params) {
Connection conn = config.build();
int rows = 0;
PreparedStatement preparedStatement=null;
try {
preparedStatement = conn.prepareStatement(mapping.getSql());
for (int i=0; i<params.size(); i++) {
preparedStatement.setString(i+1, params.get(i).toString());
}
rows = preparedStatement.executeUpdate();
if (rows != 0) {
System.out.println("修改成功,受影響行數:"+rows);
} else {
System.out.println("修改失敗,資料庫無相應資料...");
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
@Override
public int insertValue(Mapping mapping, List<Object> params) {
Connection conn = config.build();
int rows = 0;
PreparedStatement preparedStatement=null;
try {
preparedStatement = conn.prepareStatement(mapping.getSql());
for (int i=0; i<params.size(); i++) {
preparedStatement.setString(i+1, params.get(i).toString());
}
try {
rows = preparedStatement.executeUpdate();
if (rows != 0) {
System.out.println("插入成功,受影響行數:"+rows);
} else {
System.out.println("插入失敗...");
}
} catch (SQLException throwables) {
throw new RuntimeException("插入重復 \"Key\" 值資料");
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
private <T> T resultToObject(ResultSet rs, Object object) {
Object obj=null;
try {
Class<?> cls = object.getClass();
/*
這里為什么要通過class再new一個物件?
因為如果不new一個新的物件,每次回傳的都是形參上的object,
而這個object都是同一個,會導致list串列后面覆寫前面值,
*/
obj=cls.newInstance();
//獲取結果集元資料(獲取此 ResultSet 物件的列的編號、型別和屬性,)
ResultSetMetaData rd=rs.getMetaData();
for (int i = 0; i < rd.getColumnCount(); i++) {
//獲取列名
String columnName=rd.getColumnLabel(i+1);
//組合方法名
String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1);
//獲取列型別
int columnType=rd.getColumnType(i+1);
Method method=null;
switch(columnType) {
case java.sql.Types.VARCHAR:
case java.sql.Types.CHAR:
method=cls.getMethod(methodName, String.class);
method.invoke(obj, rs.getString(columnName));
break;
case java.sql.Types.INTEGER:
method=cls.getMethod(methodName, Integer.class);
method.invoke(obj, rs.getInt(columnName));
break;
default:
break;
}
}
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException | SQLException e) {
e.printStackTrace();
}
return (T) obj;
}
}
四、打包測驗
4.1 將其打成 Jar 包

4.2 創建一個Maven專案,因為需要匯入對應的包
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<!-- xml決議 -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- 自己寫的Mybatis,首先要將其放入本地倉庫 -->
<dependency>
<groupId>top.kk233</groupId>
<artifactId>SimpMybatis</artifactId>
<version>1.0.0</version>
</dependency>
?Maven匯入本地Jar包方法自行百度,這里就不贅述,
4.3 創建資料庫
這里提供一個我測驗的,你們可以自行創建其他的
CREATE DATABASE IF NOT EXISTS `test`;
USE `test`;
CREATE TABLE `user` (
`id` INT ( 10 ) NOT NULL,
`sex` VARCHAR ( 2 ) NOT NULL,
`password` VARCHAR ( 255 ) DEFAULT NULL,
`username` VARCHAR ( 255 ) DEFAULT NULL,
PRIMARY KEY ( `id` )
) ENGINE = INNODB AUTO_INCREMENT = 2 DEFAULT CHARSET = utf8;
INSERT INTO `test`.`user` ( `id`, `sex`, `password`, `username` )
VALUES
( 1, '男', '12344', '五六' ),
( 2, '女', '12643', '張三' ),
( 3, '男', '1245453', '李四' );
4.4 創建物體類
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 16:17
*/
public class User {
private Integer id;
private String sex;
private String password;
private String username;
// setter、getter略
}
4.5 創建 UserMapper 介面
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 16:17
*/
public interface UserMapper {
List<User> getUsers();
List<User> getUserBySexAndName(String sex, String username);
int deleteUserById(Integer id);
int updateUserByName(String username, String password);
int insertUser(int id, String sex, String password, String username);
}
4.6 創建 UserMapper.xml 映射檔案
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="top.kk233.mapper.UserMapper">
<select id="getUsers" resultType="top.kk233.pojo.User">
SELECT * FROM user
</select>
<select id="getUserBySexAndName" resultType="top.kk233.pojo.User">
select * from user where sex=? and username=?
</select>
<delete id="deleteUserById" resultType="top.kk233.pojo.User">
delete from user where id=?
</delete>
<update id="updateUserByName" resultType="top.kk233.pojo.User">
update user set password=? where username=?
</update>
<insert id="insertUser" resultType="top.kk233.pojo.User">
insert into user values(?,?,?,?)
</insert>
</mapper>
4.7 創建 mybatis-config.xml 資料庫組態檔
<?xml version="1.0" encoding="UTF-8"?>
<database>
<property name="driverClassName">com.mysql.jdbc.Driver</property>
<property name="url">jdbc:mysql://localhost:3306/test?useSSL=false</property>
<property name="username">root</property>
<property name="password">124760</property>
</database>
4.8 創建啟動類測驗
/**
* @author Kenelm
* @version 1.0
* @date 2020/11/22 16:24
*/
public class app {
public static void main(String[] args) {
MySqlSession sql = new MySqlSession();
UserMapper mapper = sql.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
users.forEach(System.out::println);
System.out.println("==========================");
List<User> users1 = mapper.getUserBySexAndName("女", "張三");
users1.forEach(System.out::println);
System.out.println("==========================");
mapper.deleteUserById(1);
System.out.println("==========================");
mapper.updateUserByName("五六", "女");
System.out.println("==========================");
mapper.insertUser(10, "男", "123123", "五七");
}
}
4.9 測驗結果

??測驗成功,這就是本人所手寫的Mybatis,雖然比較簡單,但還是學習到了很多東西,
??專案放在 Gitee 上有需要自行下載,覺得可以還請點個Star
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/270649.html
標籤:其他
