标签:int 数据类型 nic eof private case 工程文件 config environ
MyBatis框架的核心功能其实不难,无非就是动态代理和jdbc的操作,难的是写出来可扩展,高内聚,低耦合的规范的代码。本文完成的Mybatis功能比较简单,代码还有许多需要改进的地方,大家可以结合Mybatis源码去动手完善。
在手写自己的Mybatis框架之前,我们先来了解一下Mybatis,它的源码中使用了大量的设计模式,阅读源码并观察设计模式在其中的应用,才能够更深入的理解源码(ref:Mybatis源码解读-设计模式总结)。我们对上图进行分析总结:
基本实现
带有缓存功能的实现
5.MappedStatement是通过Mapper.xml中定义statement生成的对象。
6.参数输入执行并输出结果集,无需手动判断参数类型和参数下标位置,且自动将结果集映射为Java对象
根据上文Mybatis流程,我简化了下,分为以下步骤:
从图中可以看出,MyConfiguration负责与人交互。待读取xml后,将属性和连接数据库的操作封装在MyConfiguration对象中供后面的组件调用。本文将使用dom4j来读取xml文件,它具有性能优异和非常方便使用的特点。
我们经常在使用框架时看到Session,Session到底是什么呢?一个Session仅拥有一个对应的数据库连接。类似于一个前段请求Request,它可以直接调用exec(SQL)来执行SQL语句。从流程图中的箭头可以看出,MySqlSession的成员变量中必须得有MyExecutor和MyConfiguration去集中做调配,箭头就像是一种关联关系。我们自己的MySqlSession将有一个getMapper方法,然后使用动态代理生成对象后,就可以做数据库的操作了。
Executor是一个执行器,负责SQL语句的生成和查询缓存(缓存还没完成)的维护,也就是jdbc的代码将在这里完成,不过本文只实现了单表,有兴趣的同学可以尝试完成多表。
我们只是希望对指定的接口生成一个对象,使得执行它的时候能运行一句sql罢了,而接口无法直接调用方法,所以这里使用动态代理生成对象,在执行时还是回到MySqlSession中调用查询,最终由MyExecutor做JDBC查询。这样设计是为了单一职责,可扩展性更强。
工程文件及目录:
首先,新建一个maven项目,在pom.xml中导入以下依赖:
1 <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"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.liugh</groupId> 4 <artifactId>jpMybatis</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <packaging>jar</packaging> 7 8 <properties> 9 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 10 <maven.compiler.source>1.8</maven.compiler.source> 11 <maven.compiler.target>1.8</maven.compiler.target> 12 <java.version>1.8</java.version> 13 </properties> 14 15 <dependencies> 16 <!-- 读取xml文件 --> 17 <dependency> 18 <groupId>dom4j</groupId> 19 <artifactId>dom4j</artifactId> 20 <version>1.6.1</version> 21 </dependency> 22 23 <!-- MySQL --> 24 <dependency> 25 <groupId>mysql</groupId> 26 <artifactId>mysql-connector-java</artifactId> 27 <version>5.1.29</version> 28 </dependency> 29 </dependencies> 30 </project>
创建我们的数据库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>
然后在数据库创建test库,执行如下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‘, ‘wjp‘);
package com.jp.bean; public class User { private String id; private String username; private String password; //省略get set toString方法... }
package com.jp.mapper; import com.jp.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>
先准备封装我们读取xml配置信息的 类,即用面向对象的思想设计读取xml配置
package com.jp.config; import java.util.List; public class MapperBean { private String interfaceName; //接口名 private List<Function> list; //接口下所有方法 //省略 get set方法... }
Function对象包括sql的类型、方法名、sql语句、返回类型和参数类型。
package com.jp.config; public class Function { private String sqltype; private String funcName; private String sql; private Object resultType; private String parameterType; //省略 get set方法 }
我们实现MyConfiguration,读取并存储配置信息,建立连接
1 package com.jp.sqlSession; 2 3 import java.io.InputStream; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.Iterator; 9 import java.util.List; 10 import org.dom4j.Document; 11 import org.dom4j.DocumentException; 12 import org.dom4j.Element; 13 import org.dom4j.io.SAXReader; 14 import com.jp.config.Function; 15 import com.jp.config.MapperBean; 16 17 18 /** 19 * 读取与解析配置信息,并返回处理后的Environment 20 */ 21 public class MyConfiguration { 22 private static ClassLoader loader = ClassLoader.getSystemClassLoader(); 23 24 /** 25 * 读取数据库配置信息(config.xml信息)并建立连接connection 26 * 27 */ 28 public Connection build(String resource){ 29 try { 30 InputStream stream = loader.getResourceAsStream(resource); 31 SAXReader reader = new SAXReader(); 32 Document document = reader.read(stream); 33 Element root = document.getRootElement(); 34 return evalDataSource(root); 35 } catch (Exception e) { 36 throw new RuntimeException("error occured while evaling xml " + resource); 37 } 38 } 39 40 private Connection evalDataSource(Element node) throws ClassNotFoundException { 41 if (!node.getName().equals("database")) { 42 throw new RuntimeException("root should be <database>"); 43 } 44 String driverClassName = null; 45 String url = null; 46 String username = null; 47 String password = null; 48 //获取属性节点 49 for (Object item : node.elements("property")) { 50 Element i = (Element) item; 51 String value = getValue(i); 52 String name = i.attributeValue("name"); 53 if (name == null || value == null) { 54 throw new RuntimeException("[database]: <property> should contain name and value"); 55 } 56 //赋值 57 switch (name) { 58 case "url" : url = value; break; 59 case "username" : username = value; break; 60 case "password" : password = value; break; 61 case "driverClassName" : driverClassName = value; break; 62 default : throw new RuntimeException("[database]: <property> unknown name"); 63 } 64 } 65 66 Class.forName(driverClassName); 67 Connection connection = null; 68 try { 69 //建立数据库链接 70 connection = DriverManager.getConnection(url, username, password); 71 } catch (SQLException e) { 72 // TODO Auto-generated catch block 73 e.printStackTrace(); 74 } 75 return connection; 76 } 77 78 //获取property属性的值,如果有value值,则读取 没有设置value,则读取内容 79 private String getValue(Element node) { 80 return node.hasContent() ? node.getText() : node.attributeValue("value"); 81 } 82 83 84 /** 85 * 86 * @param path 87 * @return 88 */ 89 @SuppressWarnings("rawtypes") 90 public MapperBean readMapper(String path){ 91 MapperBean mapper = new MapperBean(); 92 try{ 93 InputStream stream = loader.getResourceAsStream(path); 94 SAXReader reader = new SAXReader(); 95 Document document = reader.read(stream); 96 Element root = document.getRootElement(); 97 mapper.setInterfaceName(root.attributeValue("nameSpace").trim()); //把mapper节点的nameSpace值存为接口名 98 List<Function> list = new ArrayList<Function>(); //用来存储方法的List 99 for(Iterator rootIter = root.elementIterator();rootIter.hasNext();) {//遍历根节点下所有子节点 100 Function fun = new Function(); //用来存储一条方法的信息 101 Element e = (Element) rootIter.next(); 102 String sqltype = e.getName().trim(); 103 String funcName = e.attributeValue("id").trim(); 104 String sql = e.getText().trim(); 105 String resultType = e.attributeValue("resultType").trim(); 106 fun.setSqltype(sqltype); 107 fun.setFuncName(funcName); 108 Object newInstance=null; 109 try { 110 newInstance = Class.forName(resultType).newInstance(); 111 } catch (InstantiationException e1) { 112 e1.printStackTrace(); 113 } catch (IllegalAccessException e1) { 114 e1.printStackTrace(); 115 } catch (ClassNotFoundException e1) { 116 e1.printStackTrace(); 117 } 118 fun.setResultType(newInstance); 119 fun.setSql(sql); 120 list.add(fun); 121 } 122 mapper.setList(list); 123 124 } catch (DocumentException e) { 125 e.printStackTrace(); 126 } 127 return mapper; 128 } 129 }
首先的成员变量里得有Excutor和MyConfiguration,代码的精髓就在getMapper的方法里。
1 package com.jp.sqlSession; 2 3 import java.lang.reflect.Proxy; 4 5 public class MySqlsession { 6 private Excutor excutor = new MyExcutor(); 7 8 private MyConfiguration myConfiguration = new MyConfiguration(); 9 10 public <T> T selectOne(String statement, Object parameter) { 11 return excutor.query(statement, parameter); 12 } 13 14 @SuppressWarnings("unchecked") 15 public <T> T getMapper(Class<T> clas) { 16 // 动态代理调用 17 return (T) Proxy.newProxyInstance(clas.getClassLoader(), new Class[] { clas }, 18 new MyMapperProxy(myConfiguration, this)); 19 } 20 }
紧接着创建Excutor和实现类:
package com.jp.sqlSession; public interface Excutor { public <T> T query(String statement,Object parameter); }
MyExcutor中封装了JDBC的操作:
1 package com.jp.sqlSession; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import com.jp.bean.User; 8 9 public class MyExcutor implements Excutor { 10 11 private MyConfiguration xmlConfiguration = new MyConfiguration(); 12 13 @Override 14 public <T> T query(String sql, Object parameter) { 15 Connection connection = getConnection(); 16 ResultSet set = null; 17 PreparedStatement pre = null; 18 try { 19 pre = connection.prepareStatement(sql); 20 // 设置参数 21 pre.setString(1, parameter.toString()); 22 set = pre.executeQuery(); 23 User u = new User(); 24 // 遍历结果集 25 while (set.next()) { 26 u.setId(set.getString(1)); 27 u.setUsername(set.getString(2)); 28 u.setPassword(set.getString(3)); 29 } 30 return (T) u; 31 } catch (SQLException e) { 32 e.printStackTrace(); 33 } finally { 34 try { 35 if (set != null) { 36 set.close(); 37 } 38 if (pre != null) { 39 pre.close(); 40 } 41 if (connection != null) { 42 connection.close(); 43 } 44 } catch (Exception e2) { 45 e2.printStackTrace(); 46 } 47 } 48 return null; 49 } 50 51 //MyConfiguration类的build函数,创建的数据库连接 52 private Connection getConnection() { 53 try { 54 Connection connection = xmlConfiguration.build("config.xml"); 55 return connection; 56 } catch (Exception e) { 57 e.printStackTrace(); 58 } 59 return null; 60 } 61 }
MyMapperProxy代理类完成xml方法和真实方法对应,执行查询:
1 package com.jp.sqlSession; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.util.List; 6 import com.jp.config.Function; 7 import com.jp.config.MapperBean; 8 9 public class MyMapperProxy implements InvocationHandler { 10 11 private MySqlsession mySqlsession; 12 13 private MyConfiguration myConfiguration; 14 15 public MyMapperProxy(MyConfiguration myConfiguration, MySqlsession mySqlsession) { 16 this.myConfiguration = myConfiguration; 17 this.mySqlsession = mySqlsession; 18 } 19 20 @Override 21 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 22 MapperBean readMapper = myConfiguration.readMapper("UserMapper.xml"); 23 // 是否是xml文件对应的接口 24 if (!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())) { 25 return null; 26 } 27 List<Function> list = readMapper.getList(); 28 if (null != list || 0 != list.size()) { 29 for (Function function : list) { 30 // id是否和接口方法名一样 31 if (method.getName().equals(function.getFuncName())) { 32 return mySqlsession.selectOne(function.getSql(), String.valueOf(args[0])); 33 } 34 } 35 } 36 return null; 37 } 38 }
package com.jp.test; import com.jp.mapper.UserMapper; import com.jp.sqlSession.MySqlsession; import com.jp.bean.User; 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); } }
https://my.oschina.net/liughDevelop/blog/1631006
标签:int 数据类型 nic eof private case 工程文件 config environ
原文地址:https://www.cnblogs.com/xdyixia/p/9420547.html