自定义MyBatis是为了深入了解MyBatis的原理

主要的调用是这样的:

//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SQLSession创建Dao接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
//5.使用代理对象执行方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//6.释放资源
session.close();
in.close();

首先第一步:将配置文件SqlMapConfig.xml转为流文件

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration> <configuration>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments> <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<!--<mappers>
<mapper resource="com/jinke/dao/UserDao.xml"/>
</mappers>-->
<!--如果是用注解来配置-->
<mappers>
<mapper class="com.jinke.dao.UserDao"/>
</mappers>
</configuration>
import java.io.InputStream;

/*使用类加载器读取配置文件的类*/
public class Resources { public static InputStream getResourceAsStream(String filePath) {
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}

第二步:解析配置文件

import com.jinke.mybatis.cfg.Configuration;
import com.jinke.mybatis.sqlsession.defaults.DefaultSqlSessionFactory;
import com.jinke.mybatis.utils.XMLConfigBuilder; import java.io.InputStream; public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream config) {
Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
return new DefaultSqlSessionFactory(cfg);
}
}

主要是通过反射将属性值保存到map中

import com.jinke.mybatis.annotations.Select;
import com.jinke.mybatis.cfg.Configuration;
import com.jinke.mybatis.cfg.Mapper;
import com.jinke.mybatis.io.Resources;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class XMLConfigBuilder {
public static Configuration loadConfiguration(InputStream config) {
Configuration cfg = new Configuration();
try { SAXReader reader = new SAXReader(); Document document = reader.read(config); Element root = document.getRootElement();
List<Element> propertyElements = root.selectNodes("//property"); for (Element propertyElement : propertyElements) {
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)) {
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
for (Element mapperElement : mapperElements) {
Attribute attribute = mapperElement.attribute("resource");
if (attribute != null) {
System.out.println("使用的是XML");
String mapperPath = attribute.getValue();
Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
cfg.setMappers(mappers);
} else {
System.out.println("使用的是注解");
String daoClassPath = mapperElement.attributeValue("class");
Map<String, Mapper> mappers = loadMapperAnnotation(daoClassPath);
cfg.setMappers(mappers);
}
}
return cfg;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
config.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return cfg;
} private static Map<String, Mapper> loadMapperConfiguration(String mapperPath) throws IOException {
InputStream in = null;
Map<String, Mapper> mappers = new HashMap<String, Mapper>();
try {
in = Resources.getResourceAsStream(mapperPath);
SAXReader reader = new SAXReader();
Document document = reader.read(in);
Element root = document.getRootElement();
String namespace = root.attributeValue("namespace");
List<Element> selectElements = root.selectNodes("//select");
for (Element selectElement : selectElements) {
String id = selectElement.attributeValue("id");
String resultType = selectElement.attributeValue("resultType");
String queryString = selectElement.getText();
String key = namespace + "." + id;
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
mappers.put(key, mapper);
}
return mappers;
} catch (Exception e) {
e.printStackTrace();
}
return mappers;
} private static Map<String, Mapper> loadMapperAnnotation(String daoClassPath) throws Exception {
Map<String, Mapper> mappers = new HashMap<String, Mapper>();
Class daoClass = Class.forName(daoClassPath);
Method[] methods = daoClass.getMethods();
for (Method method : methods) {
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if (isAnnotated) {
Mapper mapper = new Mapper();
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
Type type = method.getGenericReturnType();
if (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
Type[] types = ptype.getActualTypeArguments();
Class domainClass = (Class) types[0];
String resultType = domainClass.getName();
mapper.setResultType(resultType);
}
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className + "." + methodName;
mappers.put(key, mapper);
}
}
return mappers;
}
}

第三步:DefaultSqlSessionFactory工厂生产出DefaultSqlSession对象

import com.jinke.mybatis.cfg.Configuration;
import com.jinke.mybatis.sqlsession.SqlSession;
import com.jinke.mybatis.sqlsession.SqlSessionFactory; public class DefaultSqlSessionFactory implements SqlSessionFactory { private Configuration cfg; public DefaultSqlSessionFactory(Configuration cfg) {
this.cfg = cfg;
} public SqlSession openSession() {
return new DefaultSqlSession(cfg);
}
}

第四步:DefaultSqlSession执行动态代理

import com.jinke.mybatis.cfg.Configuration;
import com.jinke.mybatis.sqlsession.SqlSession;
import com.jinke.mybatis.sqlsession.proxy.MapperProxy;
import com.jinke.mybatis.utils.DataSourceUtil; import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException; public class DefaultSqlSession implements SqlSession { private Configuration cfg;
private Connection connection; public DefaultSqlSession(Configuration cfg) {
this.cfg = cfg;
this.connection = DataSourceUtil.getConnection(cfg);
} public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(), new Class[]{daoInterfaceClass}, new MapperProxy(cfg.getMappers(), connection));
} public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

执行sql语句

import com.jinke.mybatis.cfg.Mapper;
import com.jinke.mybatis.utils.Executor; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map; public class MapperProxy implements InvocationHandler { private Map<String, Mapper> mappers;
private Connection connection; public MapperProxy(Map<String, Mapper> mappers, Connection connection) {
this.mappers = mappers;
this.connection = connection;
} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className + "." + methodName;
Mapper mapper = mappers.get(key);
if (mapper == null) {
throw new IllegalArgumentException("传入的参数有误");
}
return new Executor().selectList(mapper, connection);
}
}
import com.jinke.mybatis.cfg.Mapper;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List; public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String queryString = mapper.getQueryString();
String resultType = mapper.getResultType();
Class domainClass = Class.forName(resultType);
pstm = conn.prepareStatement(queryString);
rs = pstm.executeQuery();
List<E> list = new ArrayList<E>();
while (rs.next()) {
E obj = (E) domainClass.newInstance();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount; i++) {
String columnName = rsmd.getColumnName(i);
Object columnValue = rs.getObject(columnName);
PropertyDescriptor pd = new PropertyDescriptor(columnName, domainClass);
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(obj, columnValue);
}
list.add(obj);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
release(pstm, rs);
}
return null;
} private void release(PreparedStatement pstm, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

最后放一张文件结构图

代码地址 https://github.com/king1039/MyBatis

欢迎关注我的微信公众号:安卓圈

自定义MyBatis的更多相关文章

  1. springboot多数据源动态切换和自定义mybatis分页插件

    1.配置多数据源 增加druid依赖 完整pom文件 数据源配置文件 route.datasource.driver-class-name= com.mysql.jdbc.Driver route.d ...

  2. 自定义Mybatis框架

    项目结构:      https://files-cdn.cnblogs.com/files/mkl7/ownMybatis.zip 1. 创建maven工程并引入坐标: <?xml versi ...

  3. 简单自定义mybatis流程!!

    ----简单自定义mybatis流程----一.首先封装daoMapperxml文件和sqlMapconfig配置文件,如何封装:(1).封装我们的Mapper.xml文件,提取名称空间namespa ...

  4. 自定义 Mybatis 框架

    分析流程 1. 引入dom4j <dependencies> <!--<dependency> <groupId>org.mybatis</groupI ...

  5. 【MyBatis】自定义 MyBatis

    自定义 MyBatis 文章源码 执行查询信息的分析 我们知道,MyBatis 在使用代理 DAO 的方式实现增删改查时只做两件事: 创建代理对象 在代理对象中调用 selectList() 配置信息 ...

  6. Springboot中以配置类方式自定义Mybatis的配置规则(如开启驼峰映射等)

    什么是自定义Mybatis的配置规则? 答:即原来在mybatis配置文件中中我们配置到<settings>标签中的内容,如下第6-10行内容: 1 <?xml version=&q ...

  7. 自定义Mybatis返回类型及注意事项

    一.自定义返回拦截器package com.yaoex.crm.service.util; import org.apache.ibatis.session.ResultContext;import ...

  8. 自定义Mybatis自动生成代码规则

    前言 大家都清楚mybatis-generate-core 这个工程提供了获取表信息到生成model.dao.xml这三层代码的一个实现,但是这往往有一个痛点,比如需求来了,某个表需要增加字段,肯定需 ...

  9. 阶段3 1.Mybatis_03.自定义Mybatis框架_3.自定义mybatis的编码-根据测试类中缺少的创建接口和类

    先认识一下这几个类.Resources是一个class SqlSessionFactoryBuilder 创建新项目 复制相关的依赖 复制之前的代码 复制到当前项目的src下 把Mybits的依赖删除 ...

随机推荐

  1. iView学习笔记(二):Table行编辑操作

    1.前端准备工作 首先新建一个项目,然后引入iView插件,配置好router npm安装iView npm install iview --save cnpm install iview --sav ...

  2. Java-驼峰命名与下划线命名互转

    package com.xsh.util; /** * String工具类 * * @author xieshuang * @date 2019-05-23 */ public class Strin ...

  3. python老师博客

    前端基础之HTML http://www.cnblogs.com/yuanchenqi/articles/6835654.html 前端基础之CSS http://www.cnblogs.com/yu ...

  4. ssm批量删除

    ssm批量删除 批量删除:顾名思义就是一次性删除多个.删除是根据前台传给后台的id,那么所谓批量删除,就是将多个id传给后台,那么如何传过去呢,前后台的交互该如何实现? 1.jsp页面,先选中所有的要 ...

  5. spring MVC核心思想

    目录  一.前言二.spring mvc 核心类与接口三.spring mvc 核心流程图 四.spring mvc DispatcherServlet说明 五.spring mvc 父子上下文的说明 ...

  6. Atcoder Beginner Contest 138 简要题解

    D - Ki 题意:给一棵有根树,节点1为根,有$Q$次操作,每次操作将一个节点及其子树的所有节点的权值加上一个值,问最后每个节点的权值. 思路:dfs序再差分一下就行了. #include < ...

  7. Linux yum 包 下载地址

    yum包网址: http://www.rpmfind.net/linux/rpm2html/search.php?query=yum

  8. 大文件上传组件webupload插件

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  9. BZOJ 3561: DZY Loves Math VI 莫比乌斯反演+复杂度分析

    推到了一个推不下去的形式,然后就不会了 ~ 看题解后傻了:我推的是对的,推不下去是因为不需要再推了. 复杂度看似很大,但其实是均摊 $O(n)$ 的,看来分析复杂度也是一个能力啊 ~ code: #i ...

  10. Hibernate的批量查询——原生sql查询

    1.查询所有的学生信息: (1)查询结果中,一条信息放入到一个数组中,从list集合中取出数组,并对数组进行遍历. public class GeneratorTest { public static ...