溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Mybatis框架設(shè)計(jì)方案

發(fā)布時(shí)間:2020-05-29 17:01:12 來(lái)源:億速云 閱讀:219 作者:鴿子 欄目:編程語(yǔ)言

一、Mybatis框架流程簡(jiǎn)介

Mybatis框架設(shè)計(jì)方案


在手寫(xiě)自己的Mybatis框架之前,我們先來(lái)了解一下Mybatis,它的源碼中使用了大量的設(shè)計(jì)模式,閱讀源碼并觀察設(shè)計(jì)模式在其中的應(yīng)用,才能夠更深入的理解源碼(ref:Mybatis源碼解讀-設(shè)計(jì)模式總結(jié))。我們對(duì)上圖進(jìn)行分析總結(jié):

  1. mybatis的配置文件有2類(lèi)

  • mybatisconfig.xml,配置文件的名稱(chēng)不是固定的,配置了全局的參數(shù)的配置,全局只能有一個(gè)配置文件。

  • Mapper.xml 配置多個(gè)statemement,也就是多個(gè)sql,整個(gè)mybatis框架中可以有多個(gè)Mappe.xml配置文件。

  1. 通過(guò)mybatis配置文件得到SqlSessionFactory

  2. 通過(guò)SqlSessionFactory得到SqlSession,用SqlSession就可以操作數(shù)據(jù)了。

  3. SqlSession通過(guò)底層的Executor(執(zhí)行器),執(zhí)行器有2類(lèi)實(shí)現(xiàn):

Mybatis框架設(shè)計(jì)方案


  • 基本實(shí)現(xiàn)

  • 帶有緩存功能的實(shí)現(xiàn)

  1. MappedStatement是通過(guò)Mapper.xml中定義statement生成的對(duì)象。

  2. 參數(shù)輸入執(zhí)行并輸出結(jié)果集,無(wú)需手動(dòng)判斷參數(shù)類(lèi)型和參數(shù)下標(biāo)位置,且自動(dòng)將結(jié)果集映射為Java對(duì)象

  • HashMap,KV格式的數(shù)據(jù)類(lèi)型

  • Java的基本數(shù)據(jù)類(lèi)型

  • POJO,java的對(duì)象

二、梳理自己的Mybatis的設(shè)計(jì)思路

根據(jù)上文Mybatis流程,我簡(jiǎn)化了下,分為以下步驟:

Mybatis框架設(shè)計(jì)方案


1.讀取xml文件,建立連接

從圖中可以看出,MyConfiguration負(fù)責(zé)與人交互。待讀取xml后,將屬性和連接數(shù)據(jù)庫(kù)的操作封裝在MyConfiguration對(duì)象中供后面的組件調(diào)用。本文將使用dom4j來(lái)讀取xml文件,它具有性能優(yōu)異和非常方便使用的特點(diǎn)。

2.創(chuàng)建SqlSession,搭建Configuration和Executor之間的橋梁

我們經(jīng)常在使用框架時(shí)看到Session,Session到底是什么呢?一個(gè)Session僅擁有一個(gè)對(duì)應(yīng)的數(shù)據(jù)庫(kù)連接。類(lèi)似于一個(gè)前段請(qǐng)求Request,它可以直接調(diào)用exec(SQL)來(lái)執(zhí)行SQL語(yǔ)句。從流程圖中的箭頭可以看出,MySqlSession的成員變量中必須得有MyExecutor和MyConfiguration去集中做調(diào)配,箭頭就像是一種關(guān)聯(lián)關(guān)系。我們自己的MySqlSession將有一個(gè)getMapper方法,然后使用動(dòng)態(tài)代理生成對(duì)象后,就可以做數(shù)據(jù)庫(kù)的操作了。

3.創(chuàng)建Executor,封裝JDBC操作數(shù)據(jù)庫(kù)

Executor是一個(gè)執(zhí)行器,負(fù)責(zé)SQL語(yǔ)句的生成和查詢(xún)緩存(緩存還沒(méi)完成)的維護(hù),也就是jdbc的代碼將在這里完成,不過(guò)本文只實(shí)現(xiàn)了單表,有興趣的同學(xué)可以嘗試完成多表。

4.創(chuàng)建MapperProxy,使用動(dòng)態(tài)代理生成Mapper對(duì)象

我們只是希望對(duì)指定的接口生成一個(gè)對(duì)象,使得執(zhí)行它的時(shí)候能運(yùn)行一句sql罷了,而接口無(wú)法直接調(diào)用方法,所以這里使用動(dòng)態(tài)代理生成對(duì)象,在執(zhí)行時(shí)還是回到MySqlSession中調(diào)用查詢(xún),最終由MyExecutor做JDBC查詢(xún)。這樣設(shè)計(jì)是為了單一職責(zé),可擴(kuò)展性更強(qiáng)。

三、實(shí)現(xiàn)自己的Mybatis

工程文件及目錄:

Mybatis框架設(shè)計(jì)方案


首先,新建一個(gè)maven項(xiàng)目,在pom.xml中導(dǎo)入以下依賴(lài):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.liugh</groupId>
 <artifactId>liugh-mybatis</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 
 <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<java.version>1.8</java.version>
	</properties>
	
	<dependencies>
	 <!-- 讀取xml文件 -->
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		
		<!-- MySQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
 </dependencies>
</project>

創(chuàng)建我們的數(shù)據(jù)庫(kù)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?useUnicode=true&characterEncoding=utf8</property>
	<property name="username">root</property>
	<property name="password">123456</property>
</database>

然后在數(shù)據(jù)庫(kù)創(chuàng)建test庫(kù),執(zhí)行如下SQL語(yǔ)句:

CREATE TABLE `user` (
 `id` varchar(64) 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`, `password`, `username`) VALUES ('1', '123456', 'liugh');

創(chuàng)建User實(shí)體類(lèi),和UserMapper接口和對(duì)應(yīng)的xml文件:

package com.liugh.bean;
public class User {
 private String id;
 private String username;
 private String password;
 //省略get set toString方法...
}
package com.liugh.mapper;
import com.liugh.bean.User;
public interface UserMapper {
	
	public User getUserById(String id); 
}
<?xml version="1.0" encoding="UTF-8"?>
<mapper nameSpace="com.liugh.mapper.UserMapper">
 <select id="getUserById" resultType ="com.liugh.bean.User">
 select * from user where id = ?
 </select>
</mapper>

基本操作配置完成,接下來(lái)我們開(kāi)始實(shí)現(xiàn)MyConfiguration:

package com.liugh.sqlSession;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.liugh.config.Function;
import com.liugh.config.MapperBean;
/**
 * 讀取與解析配置信息,并返回處理后的Environment
 */
public class MyConfiguration {
	private static ClassLoader loader = ClassLoader.getSystemClassLoader();
	/**
	 * 讀取xml信息并處理
	 */
	public Connection build(String resource){
	 try {
	 InputStream stream = loader.getResourceAsStream(resource);
			SAXReader reader = new SAXReader();
			Document document = reader.read(stream);
			Element root = document.getRootElement();
			return evalDataSource(root);
		} catch (Exception e) {
			throw new RuntimeException("error occured while evaling xml " + resource);
		}
	}
	
	private Connection evalDataSource(Element node) throws ClassNotFoundException {
 if (!node.getName().equals("database")) {
 	throw new RuntimeException("root should be <database>");
 }
		String driverClassName = null;
		String url = null;
		String username = null;
		String password = null;
		//獲取屬性節(jié)點(diǎn)
		for (Object item : node.elements("property")) {
			Element i = (Element) item;			
			String value = getValue(i);
			String name = i.attributeValue("name");
			if (name == null || value == null) {
				throw new RuntimeException("[database]: <property> should contain name and value");
			}
			//賦值
			switch (name) {
				case "url" : url = value; break;
				case "username" : username = value; break;
				case "password" : password = value; break;
				case "driverClassName" : driverClassName = value; break; 
				default : throw new RuntimeException("[database]: <property> unknown name"); 
			}
		}
		
		 Class.forName(driverClassName); 
		 Connection connection = null;
		try {
			//建立數(shù)據(jù)庫(kù)鏈接
			connection = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}
	
	//獲取property屬性的值,如果有value值,則讀取 沒(méi)有設(shè)置value,則讀取內(nèi)容
	private String getValue(Element node) {
		return node.hasContent() ? node.getText() : node.attributeValue("value");
	}
	
	
	
 @SuppressWarnings("rawtypes")
 public MapperBean readMapper(String path){
 MapperBean mapper = new MapperBean();
 try{
 	InputStream stream = loader.getResourceAsStream(path);
 			SAXReader reader = new SAXReader();
 			Document document = reader.read(stream);
 			Element root = document.getRootElement();
 mapper.setInterfaceName(root.attributeValue("nameSpace").trim()); //把mapper節(jié)點(diǎn)的nameSpace值存為接口名
 List<Function> list = new ArrayList<Function>(); //用來(lái)存儲(chǔ)方法的List
 for(Iterator rootIter = root.elementIterator();rootIter.hasNext();) {//遍歷根節(jié)點(diǎn)下所有子節(jié)點(diǎn)
 Function fun = new Function(); //用來(lái)存儲(chǔ)一條方法的信息
 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 e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				}
 fun.setResultType(newInstance);
 fun.setSql(sql);
 list.add(fun);
 }
 mapper.setList(list);
 
 } catch (DocumentException e) {
 e.printStackTrace();
 }
 return mapper;
 }
}

用面向?qū)ο蟮乃枷朐O(shè)計(jì)讀取xml配置后:

package com.liugh.config;
import java.util.List;
public class MapperBean {
	private String interfaceName; //接口名
 private List<Function> list; //接口下所有方法
 //省略 get set方法...
}

Function對(duì)象包括sql的類(lèi)型、方法名、sql語(yǔ)句、返回類(lèi)型和參數(shù)類(lèi)型。

package com.liugh.config;
public class Function {
	private String sqltype; 
 private String funcName; 
 private String sql; 
 private Object resultType; 
 private String parameterType; 
	//省略 get set方法
}

接下來(lái)實(shí)現(xiàn)我們的MySqlSession,首先的成員變量里得有Excutor和MyConfiguration,代碼的精髓就在getMapper的方法里。

package com.liugh.sqlSession;
import java.lang.reflect.Proxy;
public class MySqlsession {
	
	private Excutor excutor= new MyExcutor(); 
	
	private MyConfiguration myConfiguration = new MyConfiguration();
	
 public <T> T selectOne(String statement,Object parameter){ 
 return excutor.query(statement, parameter); 
 } 
	 
 @SuppressWarnings("unchecked")
	public <T> T getMapper(Class<T> clas){ 
 	//動(dòng)態(tài)代理調(diào)用
 return (T)Proxy.newProxyInstance(clas.getClassLoader(),new Class[]{clas},
 		new MyMapperProxy(myConfiguration,this)); 
 } 
}

緊接著創(chuàng)建Excutor和實(shí)現(xiàn)類(lèi):

package com.liugh.sqlSession;
public interface Excutor {
	public <T> T query(String statement,Object parameter); 
}

MyExcutor中封裝了JDBC的操作:

package com.liugh.sqlSession;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.liugh.bean.User;
public class MyExcutor implements Excutor{
	
	private MyConfiguration xmlConfiguration = new MyConfiguration();
	
	 @Override 
	 public <T> T query(String sql, Object parameter) { 
	 Connection connection=getConnection(); 
	 ResultSet set =null;
	 PreparedStatement pre =null;
	 try { 
	 pre = connection.prepareStatement(sql); 
	 //設(shè)置參數(shù)
	 pre.setString(1, parameter.toString());
	 set = pre.executeQuery(); 
	 User u=new User(); 
	 //遍歷結(jié)果集
	 while(set.next()){ 
	 u.setId(set.getString(1));
	 u.setUsername(set.getString(2)); 
	 u.setPassword(set.getString(3));
	 } 
	 return (T) u; 
	 } catch (SQLException e) { 
	 e.printStackTrace(); 
	 } finally{
	 try{ 
	 if(set!=null){ 
	 	 set.close(); 
	 }if(pre!=null){ 
	 	 pre.close(); 
	 }if(connection!=null){ 
	 	 connection.close(); 
	 } 
	 }catch(Exception e2){ 
	 e2.printStackTrace(); 
	 } 
	 } 
	 return null; 
	 } 
	 
	 private Connection getConnection() { 
	 try { 
	 Connection connection =xmlConfiguration.build("config.xml");
	 return connection; 
	 } catch (Exception e) { 
	 e.printStackTrace(); 
	 } 
	 return null; 
	 } 
}

MyMapperProxy代理類(lèi)完成xml方法和真實(shí)方法對(duì)應(yīng),執(zhí)行查詢(xún):

package com.liugh.sqlSession;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import com.liugh.config.Function;
import com.liugh.config.MapperBean;
public class MyMapperProxy implements InvocationHandler{
	
	private MySqlsession mySqlsession; 
	
	private MyConfiguration myConfiguration;
 
 public MyMapperProxy(MyConfiguration myConfiguration,MySqlsession mySqlsession) { 
 this.myConfiguration=myConfiguration; 
 this.mySqlsession=mySqlsession; 
 } 
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		MapperBean readMapper = myConfiguration.readMapper("UserMapper.xml");
		//是否是xml文件對(duì)應(yīng)的接口
		if(!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())){
			return null; 
		}
		List<Function> list = readMapper.getList();
		if(null != list || 0 != list.size()){
			for (Function function : list) {
			//id是否和接口方法名一樣
			 if(method.getName().equals(function.getFuncName())){ 
		 return mySqlsession.selectOne(function.getSql(), String.valueOf(args[0])); 
		 } 
			}
		}
	 return null; 
	}
}

到這里,就完成了自己的Mybatis框架,我們測(cè)試一下:

package com.liugh;
import com.liugh.bean.User;
import com.liugh.mapper.UserMapper;
import com.liugh.sqlSession.MySqlsession;
public class TestMybatis {
	
 public static void main(String[] args) { 
 MySqlsession sqlsession=new MySqlsession(); 
 UserMapper mapper = sqlsession.getMapper(UserMapper.class); 
 User user = mapper.getUserById("1"); 
 System.out.println(user);
 } 
}

執(zhí)行結(jié)果:

Mybatis框架設(shè)計(jì)方案


查詢(xún)一個(gè)不存在的用戶試試:

Mybatis框架設(shè)計(jì)方案


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI