做网站找哪家公司好,wordpress设置页面缓存,专业做化妆品的网站有哪些,莱芜都市论坛自定义简易Mybatis框架
Mybatis执行流程分析
Mybatis代码编写流程: Mybatis配置文件加载过程:
需求分析及技术概述
根据上述的功能结构图, 得出如下需求:
1. 需要具有配置文件加载模块.
2. 支持使用构建者进行SessionFactory构建.
3. 支持使用工厂模式构建Session对象.
4.…自定义简易Mybatis框架
Mybatis执行流程分析
Mybatis代码编写流程: Mybatis配置文件加载过程:
需求分析及技术概述
根据上述的功能结构图, 得出如下需求:
1. 需要具有配置文件加载模块.
2. 支持使用构建者进行SessionFactory构建.
3. 支持使用工厂模式构建Session对象.
4. 可以使用代理模式, 构建DAO接口实现类对象.
5. 使用反射机制, 封装ResultSet结果集.
6. 支持使用.xml文件编写SQL语句.
7. 支持使用注解方式进行SQL查询.项目技术要点 1. 解析UserDao.xml; SqlMapConfig.xml需要使用dom4j, xpath技术2. 使用Configuration类(类似于Map结构)存储SqlMapConfig中配置信息3. SqlMapConfig中包含连接池, 使用DataSource类根据配置信息, 创建连接池4. 使用构建者, 工厂, 代理模式开发5. 使用Java反射机制, 自定义注解.项目搭建(本项目只构建Select * from tableName; 主要用于理解Mybatis执行过程)
本项目使用maven进行构建, pom.xml文件需引入如下依赖包: dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.6/version/dependencydependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.17/version/dependency
!-- 使用dom4j与xpath解析xml--dependencygroupIddom4j/groupIdartifactIddom4j/artifactIdversion1.6.1/version/dependency
!-- xpath技术--dependencygroupIdjaxen/groupIdartifactIdjaxen/artifactIdversion1.1.6/version/dependency项目目录结构: 本项目分为如下几块内容:
配置文件加载(包括SqlMapConfig.xml; Mapper.xml, 注解).
配置数据源.
Session工厂
SqlSession第一部分内容如下:
配置文件加载类实体编写(用于封装SqlMapConfig.xml文件内容):
/*** 自定义Mybatis的配置文件* author regotto*/
public class Configuration {private String driver;private String username;private String url;private String password;private MapString, Mapper mappers new HashMap(16);//....属性get, set方法
}注解定义
/*** select语句的注解, 运行期有效, 用于修饰方法* author regotto*/
Retention(RetentionPolicy.RUNTIME)
Target(ElementType.METHOD)
public interface Select {/*** 配置SQL语句* return*/String value();
}工具类准备(Xml文件解析, 数据源配置, Sql执行结果集封装): 获取XML配置文件的输入流:
public class Resources {public static InputStream getResourceAsStream(String filePath) {return Resources.class.getClassLoader().getResourceAsStream(filePath);}
}Xml文件解析(将配置文件内容解析后, 并将其封装到Configuration实体中)
public class XMLConfigBuilder {/*** 解析主配置文件把里面的内容填充到DefaultSqlSession所需要的地方* 使用的技术 dom4jxpath*/public static Configuration loadConfiguration(InputStream config){try{//定义封装连接信息的配置对象mybatis的配置对象Configuration cfg new Configuration();//1.获取SAXReader对象SAXReader reader new SAXReader();//2.根据字节输入流获取Document对象Document document reader.read(config);//3.获取根节点Element root document.getRootElement();//4.使用xpath中选择指定节点的方式获取所有property节点ListElement propertyElements root.selectNodes(//property);//5.遍历节点for(Element propertyElement : propertyElements){//判断节点是连接数据库的哪部分信息//取出name属性的值String name propertyElement.attributeValue(name);if(driver.equals(name)){String driver propertyElement.attributeValue(value);cfg.setDriver(driver);}if(url.equals(name)){String url propertyElement.attributeValue(value);cfg.setUrl(url);}if(username.equals(name)){String username propertyElement.attributeValue(value);cfg.setUsername(username);}if(password.equals(name)){//表示密码//获取property标签value属性的值String password propertyElement.attributeValue(value);cfg.setPassword(password);}}//取出mappers中的所有mapper标签判断他们使用了resource还是class属性ListElement mapperElements root.selectNodes(//mappers/mapper);//遍历集合for(Element mapperElement : mapperElements){//判断mapperElement使用的是哪个属性Attribute attribute mapperElement.attribute(resource);//在mapper中只有两种属性: resource, classif(attribute ! null){//表示有resource属性用的是XML, 取出属性的值String mapperPath attribute.getValue();//获取属性的值com/itheima/dao/IUserDao.xml//把映射配置文件的内容获取出来封装成一个mapMapString,Mapper mappers loadMapperConfiguration(mapperPath);//给configuration中的mappers赋值cfg.setMappers(mappers);}else{//表示没有resource属性用的是注解 获取class属性的值String daoClassPath mapperElement.attributeValue(class);//根据daoClassPath获取封装的必要信息MapString, Mapper mappers loadMapperAnnotation(daoClassPath);//给configuration中的mappers赋值cfg.setMappers(mappers);}}//返回Configurationreturn cfg;}catch(Exception e){throw new RuntimeException(e);}finally{try {config.close();}catch(Exception e){e.printStackTrace();}}}/*** 根据传入的参数解析XML并且封装到Map中* param mapperPath 映射配置文件的位置* return map中包含了获取的唯一标识key是由dao的全限定类名和方法名组成* 以及执行所需的必要信息value是一个Mapper对象里面存放的是执行的SQL语句和要封装的实体类全限定类名(ResultSet的类型)*/private static MapString,Mapper loadMapperConfiguration(String mapperPath)throws IOException {InputStream in null;try{//定义返回值对象MapString,Mapper mappers new HashMapString,Mapper(16);//1.根据路径获取字节输入流in Resources.getResourceAsStream(mapperPath);//2.根据字节输入流获取Document对象SAXReader reader new SAXReader();Document document reader.read(in);//3.获取根节点Element root document.getRootElement();//4.获取根节点的namespace属性取值String namespace root.attributeValue(namespace);//是组成map中key的部分//5.获取所有的select节点ListElement selectElements root.selectNodes(//select);//6.遍历select节点集合for(Element selectElement : selectElements){//取出id属性的值 组成map中key的部分String id selectElement.attributeValue(id);//取出resultType属性的值 组成map中value的部分String resultType selectElement.attributeValue(resultType);//取出文本内容 组成map中value的部分String queryString selectElement.getText();//创建KeyString key namespace.id;//创建ValueMapper mapper new Mapper();mapper.setQueryString(queryString);mapper.setResultType(resultType);//把key和value存入mappers中mappers.put(key,mapper);}return mappers;}catch(Exception e){throw new RuntimeException(e);}finally{in.close();}}/*** 根据传入的参数得到dao中所有被select注解标注的方法。* 根据方法名称和类名以及方法上注解value属性的值组成Mapper的必要信息* param daoClassPath* return*/private static MapString,Mapper loadMapperAnnotation(String daoClassPath)throws Exception{//定义返回值对象MapString,Mapper mappers new HashMapString, Mapper();//1.得到dao接口的字节码对象Class daoClass Class.forName(daoClassPath);//2.得到dao接口中的方法数组Method[] methods daoClass.getMethods();//3.遍历Method数组for(Method method : methods){//取出每一个方法判断是否有select注解boolean isAnnotated method.isAnnotationPresent(Select.class);if(isAnnotated){//创建Mapper对象Mapper mapper new Mapper();//取出注解的value属性值Select selectAnno method.getAnnotation(Select.class);String queryString selectAnno.value();mapper.setQueryString(queryString);//获取当前方法的返回值且返回值必须具有泛型(Generic泛型的意思)// ListUserType type method.getGenericReturnType();//判断type是不是参数化的类型if(type instanceof ParameterizedType){//强转ParameterizedType ptype (ParameterizedType)type;//得到参数化类型中的实际类型参数, 因为像MapK,V这种存在多个泛型, 所以Type是数组Type[] types ptype.getActualTypeArguments();//取出第一个, 我们的ListUser只有一个, 所以取出第一个Class domainClass (Class)types[0];//获取domainClass的类名String resultType domainClass.getName();//给Mapper赋值mapper.setResultType(resultType);}//组装key的信息//获取方法的名称String methodName method.getName();String className method.getDeclaringClass().getName();String key className.methodName;//给map赋值mappers.put(key,mapper);}}return mappers;}
} 数据源配置
//获得一个Connection对象
public class DataSource {public static Connection getConnection(Configuration configuration) {try {Class.forName(configuration.getDriver());return DriverManager.getConnection(configuration.getUrl(),configuration.getUsername(),configuration.getPassword());} catch (Exception e) {throw new RuntimeException(e);}}
}结果集封装(Sql执行后的ResultSet封装)
/*** author regotto* 负责执行SQL语句并且封装结果集*/
public class Executor {public E ListE selectList(Mapper mapper, Connection conn) {PreparedStatement pstm null;ResultSet rs null;try {//1.取出mapper中的数据// select * from userString queryString mapper.getQueryString();//com.regotto.domain.UserString resultType mapper.getResultType();Class domainClass Class.forName(resultType);//2.获取PreparedStatement对象pstm conn.prepareStatement(queryString);//3.执行SQL语句获取结果集rs pstm.executeQuery();//4.封装结果集ListE list new ArrayListE();//定义返回值while(rs.next()) {//实例化要封装的实体类对象E obj (E)domainClass.newInstance();//取出结果集的元信息ResultSetMetaDataResultSetMetaData rsmd rs.getMetaData();//取出总列数int columnCount rsmd.getColumnCount();//遍历总列数for (int i 1; i columnCount; i) {//获取每列的名称列名的序号是从1开始的String columnName rsmd.getColumnName(i);//根据得到列名获取每列的值Object columnValue rs.getObject(columnName);//给obj赋值使用Java内省机制借助PropertyDescriptor实现属性的封装, 底层还是反射机制//获取对应domainClass这个类中的columnName的所有操作//要求实体类的属性和数据库表的列名保持一种PropertyDescriptor pd new PropertyDescriptor(columnName,domainClass);//获取它的写入方法(即setXXX(...))Method writeMethod pd.getWriteMethod();//把获取的列的值给对象赋值(即obj.setXXX(columnValue))writeMethod.invoke(obj,columnValue);}//把赋好值的对象加入到集合中list.add(obj);}return list;} catch (Exception e) {throw new RuntimeException(e);} finally {release(pstm,rs);}}private void release(PreparedStatement pstm,ResultSet rs){if(rs ! null){try {rs.close();}catch(Exception e){e.printStackTrace();}}if(pstm ! null){try {pstm.close();}catch(Exception e){e.printStackTrace();}}}
}第二部分内容:
SqlSession工厂(此部分使用工厂模型, 构建者模型): SqlSession工厂接口:
/*** SqlSessionFactory, 制定Session* author regotto*/
public interface SqlSessionFactory {/*** 返回一个SqlSession对象* return sqlSession*/SqlSession openSession();
}工厂建造器:
/*** 根据配置文件创建SqlSessionFactory* author regotto*/
public class SqlSessionFactoryBuilder {public SqlSessionFactory build(InputStream inputStream) {Configuration configuration XMLConfigBuilder.loadConfiguration(inputStream);return new DefaultSqlSessionFactory(configuration);}
}默认Session工厂:
/*** 默认的SqlSessionFactory实现* author regotto*/
public class DefaultSqlSessionFactory implements SqlSessionFactory {private Configuration configuration;public DefaultSqlSessionFactory(Configuration configuration) {this.configuration configuration;}/*** 创建一个默认的Session* return*/Overridepublic SqlSession openSession() {return new DefaultSqlSession(configuration);}
}第三部分内容:
SqlSession Mapper实体:
/***封装XXXDao.xml中的resultType和SQL语句* author regotto*/
public class Mapper {private String resultType;private String queryString;//get, set方法...SqlSession接口:
public interface SqlSession {/*** 通过tClass获得代理对象* param daoInterfaceClass* param T* return 代理对象*/T T getMapper(ClassT daoInterfaceClass);/*** 关闭Session资源*/void close();
}MapperProxy(生成Dao接口代理类):
/*** 代理对象* author regotto*/
public class MapperProxy implements InvocationHandler {/*** String内存储*/private MapString, Mapper mappers;private Connection connection;public MapperProxy(MapString, Mapper mappers, Connection connection) {this.mappers mappers;this.connection connection;}/*** 方法增强, 调用selectList* 在此处执行SQL, 对数据库进行操作* param proxy 代理对象* param method 执行方法* param args 执行方法的参数* return Object 返回代理对象* throws Throwable*/Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {String methodName method.getName();//获取方法所在的类名String className method.getDeclaringClass().getName();String key className . methodName;//查看XXXDao.xml中是否有代理对象对应的类和方法Mapper mapper mappers.get(key);if (mapper null) {throw new IllegalArgumentException(传入的Class对象错误);}return new Executor().selectList(mapper, connection);}
}默认SqlSession实现:
/*** 默认的Session* author regotto*/
public class DefaultSqlSession implements SqlSession {/*** 封装SqlMapConfig配置信息* 包含DataSource, Mappers(封装XXXDao.xml的namespace, sql标签的id, returnType, sql语句)*/private Configuration configuration;/*** 数据库连接对象*/private Connection connection;public DefaultSqlSession(Configuration configuration) {this.configuration configuration;this.connection DataSource.getConnection(configuration);}/*** 创建代理对象* param daoInterfaceClass 需要创建代理对象的class* param T 针对所有的class* return 代理对象*/Overridepublic T T getMapper(ClassT daoInterfaceClass) {return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),new Class[]{daoInterfaceClass},new MapperProxy(configuration.getMappers(), connection));}/*** 释放资源*/Overridepublic void close() {if (connection ! null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}
}测试类:
/*** author regotto*/
public class MybatisTest {public static void main(String[] args) throws Exception {InputStream inputStream Resources.getResourceAsStream(SqlMapConfig.xml);SqlSessionFactoryBuilder sessionFactoryBuilder new SqlSessionFactoryBuilder();SqlSessionFactory sessionFactory sessionFactoryBuilder.build(inputStream);SqlSession sqlSession sessionFactory.openSession();//获得代理对象UserDao userDao sqlSession.getMapper(UserDao.class);ListUser users userDao.findAll();for (User u: users) {System.out.println(u);}sqlSession.close();inputStream.close();}
}总结
断点调试, 理解Mybatis执行过程, 根据Mybatis执行过程, 模拟实现. 遇到问题, 理清思路, debug调试.