創(chuàng)新互聯(lián)主要從事成都做網(wǎng)站、網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)瓦房店,十余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108
在手寫自己的Mybatis框架之前,我們先來了解一下Mybatis,它的源碼中使用了大量的設(shè)計(jì)模式,閱讀源碼并觀察設(shè)計(jì)模式在其中的應(yīng)用,才能夠更深入的理解源碼(ref:Mybatis源碼解讀-設(shè)計(jì)模式總結(jié))。我們對(duì)上圖進(jìn)行分析總結(jié):
mybatis的配置文件有2類
mybatisconfig.xml,配置文件的名稱不是固定的,配置了全局的參數(shù)的配置,全局只能有一個(gè)配置文件。
Mapper.xml 配置多個(gè)statemement,也就是多個(gè)sql,整個(gè)mybatis框架中可以有多個(gè)Mappe.xml配置文件。
通過mybatis配置文件得到SqlSessionFactory
通過SqlSessionFactory得到SqlSession,用SqlSession就可以操作數(shù)據(jù)了。
SqlSession通過底層的Executor(執(zhí)行器),執(zhí)行器有2類實(shí)現(xiàn):
基本實(shí)現(xiàn)
帶有緩存功能的實(shí)現(xiàn)
MappedStatement是通過Mapper.xml中定義statement生成的對(duì)象。
參數(shù)輸入執(zhí)行并輸出結(jié)果集,無需手動(dòng)判斷參數(shù)類型和參數(shù)下標(biāo)位置,且自動(dòng)將結(jié)果集映射為Java對(duì)象
HashMap,KV格式的數(shù)據(jù)類型
Java的基本數(shù)據(jù)類型
POJO,java的對(duì)象
根據(jù)上文Mybatis流程,我簡化了下,分為以下步驟:
1.讀取xml文件,建立連接
從圖中可以看出,MyConfiguration負(fù)責(zé)與人交互。待讀取xml后,將屬性和連接數(shù)據(jù)庫的操作封裝在MyConfiguration對(duì)象中供后面的組件調(diào)用。本文將使用dom4j來讀取xml文件,它具有性能優(yōu)異和非常方便使用的特點(diǎn)。
2.創(chuàng)建SqlSession,搭建Configuration和Executor之間的橋梁
我們經(jīng)常在使用框架時(shí)看到Session,Session到底是什么呢?一個(gè)Session僅擁有一個(gè)對(duì)應(yīng)的數(shù)據(jù)庫連接。類似于一個(gè)前段請(qǐng)求Request,它可以直接調(diào)用exec(SQL)來執(zhí)行SQL語句。從流程圖中的箭頭可以看出,MySQLSession的成員變量中必須得有MyExecutor和MyConfiguration去集中做調(diào)配,箭頭就像是一種關(guān)聯(lián)關(guān)系。我們自己的MySqlSession將有一個(gè)getMapper方法,然后使用動(dòng)態(tài)代理生成對(duì)象后,就可以做數(shù)據(jù)庫的操作了。
3.創(chuàng)建Executor,封裝JDBC操作數(shù)據(jù)庫
Executor是一個(gè)執(zhí)行器,負(fù)責(zé)SQL語句的生成和查詢緩存(緩存還沒完成)的維護(hù),也就是jdbc的代碼將在這里完成,不過本文只實(shí)現(xiàn)了單表,有興趣的同學(xué)可以嘗試完成多表。
4.創(chuàng)建MapperProxy,使用動(dòng)態(tài)代理生成Mapper對(duì)象
我們只是希望對(duì)指定的接口生成一個(gè)對(duì)象,使得執(zhí)行它的時(shí)候能運(yùn)行一句sql罷了,而接口無法直接調(diào)用方法,所以這里使用動(dòng)態(tài)代理生成對(duì)象,在執(zhí)行時(shí)還是回到MySqlSession中調(diào)用查詢,最終由MyExecutor做JDBC查詢。這樣設(shè)計(jì)是為了單一職責(zé),可擴(kuò)展性更強(qiáng)。
工程文件及目錄:
首先,新建一個(gè)maven項(xiàng)目,在pom.xml中導(dǎo)入以下依賴:
4.0.0 com.liugh liugh-mybatis 0.0.1-SNAPSHOT jar UTF-8 1.8 1.8 1.8 dom4j dom4j 1.6.1 mysql mysql-connector-java 5.1.29
創(chuàng)建我們的數(shù)據(jù)庫xml配置文件:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8 root 123456
然后在數(shù)據(jù)庫創(chuàng)建test庫,執(zhí)行如下SQL語句:
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í)體類,和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); }
基本操作配置完成,接下來我們開始實(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"); } 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]: 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]: unknown name"); } } Class.forName(driverClassName); Connection connection = null; try { //建立數(shù)據(jù)庫鏈接 connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } //獲取property屬性的值,如果有value值,則讀取 沒有設(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 list = new ArrayList (); //用來存儲(chǔ)方法的List for(Iterator rootIter = root.elementIterator();rootIter.hasNext();) {//遍歷根節(jié)點(diǎn)下所有子節(jié)點(diǎn) Function fun = new Function(); //用來存儲(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 Listlist; //接口下所有方法 //省略 get set方法... }
Function對(duì)象包括sql的類型、方法名、sql語句、返回類型和參數(shù)類型。
package com.liugh.config; public class Function { private String sqltype; private String funcName; private String sql; private Object resultType; private String parameterType; //省略 get set方法 }
接下來實(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(); publicT selectOne(String statement,Object parameter){ return excutor.query(statement, parameter); } @SuppressWarnings("unchecked") public T getMapper(Class 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)類:
package com.liugh.sqlSession; public interface Excutor { publicT 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 publicT 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代理類完成xml方法和真實(shí)方法對(duì)應(yīng),執(zhí)行查詢:
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; } Listlist = 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é)果:
查詢一個(gè)不存在的用戶試試: