自定义Mybatis

前期准备

设计思想如下:

利用XML解析核心配置文件,得到数据库连接,再解析映射文件,得到接口与SQL的联系
利用动态代理对接口进行增强
当调用接口某个方法的时候,从存储了接口方法与SQL对应的集合取出SQL,并执行SQL,把执行结果进行封装,从而完成mybatis的工作

涉及到的技术如下:

工厂模式(Factory 工厂模式)、构造者模式(Builder 模式)、代理模式,反射,自定义注解,注解的反射,xml 解析,数据库元数据,元数据的反射等。

涉及到的依赖如下:

dom4j 负责解析XML
mysql-connector-java 数据库连接驱动
jaxen dom4j 的依赖包

设计到的代码文件如下:

在这里插入图片描述

创建一个普通的Maven工程

在这里插入图片描述

工程信息如下:(自定义)

在这里插入图片描述

引入相关坐标

<dependencies>
<!-- 解析 xml 的 dom4j -->
    <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.47</version>
    </dependency>
<!-- dom4j 的依赖包 jaxen -->
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.2.0</version>
    </dependency>
</dependencies>

引入工具类到项目中

XMLConfigBuilder.java 用于解析配置文件

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
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 {
    /**
     * 用来存储namespace文件名
     */
    private static volatile String simpleName;

    /**
     * 解析主配置文件,把里面的内容填充到 DefaultSqlSession 所需要的地方
     *
     * @param session
     * @param inputStream
     */
    public static void loadConfiguration(DefaultSqlSession session, InputStream inputStream) throws IOException {
        //定义封装连接信息的配置对象
        Configuration configuration = new Configuration();
        SAXReader reader = new SAXReader();
        //根据字节流获取Document对象
        try {
            Document doc = reader.read(inputStream);
            //获取根节点
            Element rootElement = doc.getRootElement();
            //使用xpath中选择指定节点的方式,获取所有property节点
            List<Element> propertyElements = rootElement.selectNodes("//property");
            //遍历节点
            for (Element element : propertyElements) {
                //判断节点是连接数据库的哪部分信息
                //取出name属性的值
                String name = element.attributeValue("name");
                if ("driver".equals(name)) {
                    //表示驱动
                    //获取property标签value属性的值
                    String driver = element.attributeValue("value");
                    configuration.setDriver(driver);
                }
                if ("url".equals(name)) {
                    //表示连接地址
                    //获取property标签value属性的值
                    String url = element.attributeValue("value");
                    configuration.setUrl(url);
                }
                if ("username".equals(name)) {
                    //表示用户
                    //获取property标签value属性的值
                    String username = element.attributeValue("value");
                    configuration.setUsername(username);
                }
                if ("password".equals(name)) {
                    //表示密码
                    //获取property标签value属性的值
                    String password = element.attributeValue("value");
                    configuration.setPassword(password);
                }
            }
            //取出 mappers 中的所有 mapper 标签,判断他们使用了 resource 还是 class 属性
            List<Element> mapperElements = rootElement.selectNodes("//mappers/mapper");
            for (Element mapperElement : mapperElements) {
                Attribute attribute = mapperElement.attribute("resource");
                if (attribute != null) {
                    System.out.println("使用的是XML");
                    //表示有resource属性,即使用的XML
                    //取出属性的值
                    String mapperPath = attribute.getValue();
                    Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
                    //给configuration中的mapper赋值
                    configuration.getMapMap().put(simpleName, mappers);
                } else {
                    System.out.println("使用的是注解");
                    //获取 class 属性的值
                    String daoClassPath = mapperElement.attributeValue("class");
                    //根据 daoClassPath 获取封装的必要信息
                    Map<String, Mapper> mappers = loadMapperConfiguration(daoClassPath);
                    //给 configuration 中的 mappers 赋值
                    configuration.getMapMap().put(simpleName, mappers);
                }
            }
            //把配置对象传递给 DefaultSqlSession
            session.setConfiguration(configuration);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据传入的参数,解析 XML,并且封装到 Map 中
     *
     * @param mapperPath 映射配置文件的位置
     * @return map 中包含了获取的唯一标识(key 是由 dao 的全限定类名和方法名组成)
     * 以及执行所需的必要信息(value 是一个 Mapper 对象,里面存放的是执行的 SQL 语句和
     * 要封装的实体类全限定类名)
     */
    public static Map<String, Mapper> loadMapperConfiguration(String mapperPath) throws IOException {

        try {
            Map<String, Mapper> mappers = new HashMap<>();
            //根据路径获取字节输入流
            InputStream inputStream = Resources.getResourceAsStream(mapperPath);

            //根据字节输入流获取 Document 对象
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            //获取根节点
            Element rootElement = document.getRootElement();
            //获取根节点的 namespace 属性取值
            String namespace = rootElement.attributeValue("namespace");
            simpleName = namespace;
            //获取所有的 select 节点
            List<Element> selectedElements = rootElement.selectNodes("//select");
            //遍历 select 节点集合
            for (Element element : selectedElements) {
                //取出 id 属性的值 组成 map 中 key 的部分
                String id = element.attributeValue("id");
                //取出 resultType 属性的值 组成 map 中 value 的部分
                String resultType = element.attributeValue("resultType");
                //取出文本内容 组成 map 中 value 的部分
                String queryString = element.getText();
                //创建  Key
                String key = namespace + "." + id;
                //创建 Value
                Mapper 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);
        }
    }
}

Executor.java 负责执行 SQL 语句,并且封装结果集

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Executor {
    /**
     * 负责接收集合数据
     *
     * @param mapper 需要执行的SQL语句
     * @param conn   数据库连接对象
     * @param <E>    数据泛型
     * @return
     */
    public <E> List<E> selectList(Mapper mapper, Connection conn) {
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            String queryString = mapper.getQueryString();

            String resultType = mapper.getResultType();

            Class domainClass = Class.forName(resultType);

            pst = conn.prepareStatement(queryString);
            rs = pst.executeQuery();
            List<E> list = new ArrayList<E>();
            while (rs.next()) {
                //实例化要封装的实体类对象
                E obj = (E) domainClass.newInstance();
                //取出结果集的元信息:ResultSetMetaData
                ResultSetMetaData red = rs.getMetaData();
                //取出总列数
                int columnCount = red.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    //获取每列的名称,列名的序号是从 1 开始的
                    String columnName = red.getColumnName(i);
                    //根据得到列名,获取每列的值
                    Object columnValue = rs.getObject(columnName);
                    //给 obj 赋值:使用 Java 内省机制(借助 PropertyDescriptor 实现属性的封装)
                    //要求:实体类的属性和数据库表的列名保持一种
                    PropertyDescriptor pd = new PropertyDescriptor(columnName, domainClass);
                    //获取它的写入方法
                    Method wrapperMethod = pd.getWriteMethod();
                    //把获取的列的值,给对象赋值
                    wrapperMethod.invoke(obj, columnValue);
                }
                //把赋好值的对象加入到集合中
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            release(pst, rs);
        }
    }

    /**
     * 关闭资源
     *
     * @param pst
     * @param rs
     */
    private void release(PreparedStatement pst, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

DataSourceUtil.java 数据源的工具类

import java.sql.Connection;
import java.sql.DriverManager;
public class DataSourceUtil {
    /**
     * 获取数据库连接
     * @param configuration 数据库文件配置
     * @return
     */
    public static Connection getConnection(Configuration configuration) {
        try {
            Class.forName(configuration.getDriver());
            Connection connection = DriverManager.getConnection(configuration.getUrl(), configuration.getUsername(), configuration.getPassword());
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

SqlMapConfig.xml 自定义mybatis的核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<environments default="mysql">
    <environment id="mysql">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql:///mybatis01?useSSL=false"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </dataSource>
    </environment>
    <!-- 映射文件 -->
    <mappers>
        <!-- <mapper resource=""/> -->
        <mapper resource="mapper/UserDao.xml"/>
    </mappers>
</environments>

Resources.java 读取配置文件类

import java.io.InputStream;
public class Resources {
    /**
     * 用于加载 xml 文件,并且得到一个流对象
     *
     * @param mapperPath
     * @return
     */
    public static InputStream getResourceAsStream(String mapperPath) {
        return Resources.class.getClassLoader().getResourceAsStream(mapperPath);
    }
}

Mapper.java 用于封装查询时的必要信息:要执行的 SQL 语句和实体类的全限定类名

public class Mapper {
    /**
     * Sql
     */
    private String queryString;
    /**
     * 结果类型的全限定类名
     */
    private String resultType;

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public String getResultType() {
        return resultType;
    }

    public void setResultType(String resultType) {
        this.resultType = resultType;
    }
}

Configuration.java 核心配置类

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Configuration {
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 地址
     */
    private String url;
    /**
     * 驱动
     */
    private String driver;
    /**
     * map 集合 Map<唯一标识,Mapper> 用于保存映射文件中的 sql 标识及 sql 语句
     */
    private final Map<String, Map<String, Mapper>> mapMap = new ConcurrentHashMap<>();

    public Map<String, Map<String, Mapper>> getMapMap() {
        return mapMap;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

}

SqlSessionFactoryBuilder.java 构建者

import java.io.InputStream;
public class SqlSessionFactoryBuilder {
    /**
     * 根据传入的流,实现对 SqlSessionFactory 的创建
     * @param inputStream 它就是 SqlMapConfig.xml 的配置以及里面包含的 UserDao.xml 的配置
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream) {
        DefaultSqlSessionFactory factory = new DefaultSqlSessionFactory();
        factory.setConfig(inputStream);
        return factory;
    }
}

SqlSessionFactory.java SqlSessionFactory 的接口

public interface SqlSessionFactory {
    /**
     *  创建一个新的 SqlSession 对象
     * @return
     */
    SqlSession openSession();
}

DefaultSqlSessionFactory.java SqlSessionFactory 的默认实现

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    /**
     * 获取输入流
     */
    private InputStream config = null;

    public void setConfig(InputStream config) {
        this.config = config;
    }

    @Override
    public SqlSession openSession() {
        DefaultSqlSession session = new DefaultSqlSession();
        try {
            XMLConfigBuilder.loadConfiguration(session, config);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return session;
    }
}

SqlSession.java 操作数据库的核心对象

public interface SqlSession {
    /**
     * 创建Dao接口的代理对象
     * @param daoClazz
     * @param <T>
     * @return
     */
    <T> T getMapper(Class<T> daoClazz);

    /**
     * 释放资源
     */
    void close();
}

SqlSession 的具体实现

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {
    /**
     * 核心配置对象
     */
    private Configuration configuration;
    /**
     * 数据库连接对象
     */
    private Connection connection;

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 调用 DataSourceUtils 工具类获取连接
     *
     * @return
     */
    public Connection getConnection() {
        try {
            connection = DataSourceUtil.getConnection(configuration);
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建Dao接口的代理对象
     *
     * @param daoClazz
     * @return
     */
    @Override
    public <T> T getMapper(Class<T> daoClazz) {
        connection = getConnection();
        Map<String, Mapper> mappers = configuration.getMapMap().get(daoClazz.getName());
        T proxyInstance = (T) Proxy.newProxyInstance(daoClazz.getClassLoader(), new Class[]{daoClazz}, new MapperProxyFactory(mappers, connection));
        return proxyInstance;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        try {
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MapperProxyFactory.java 用于创建代理对象是增强方法


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;
public class MapperProxyFactory implements InvocationHandler {
    /**
     *
     */
    private Map<String, Mapper> mappers;
    /**
     *
     */
    private Connection connection;

    public MapperProxyFactory(Map<String, Mapper> mappers, Connection connection) {
        this.mappers = mappers;
        this.connection = connection;
    }

    /**
     * 对当前正在执行的方法进行增强
     *
     * @param proxy  类的Class对象
     * @param method 方法
     * @param args   参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //取出方法名
        String methodName = method.getName();
        //取出方法所在类名
        String className = method.getDeclaringClass().getName();
        //拼接成Key
        String key = className + "." + methodName;
        //使用 key 取出 mapper
        Mapper mapper = mappers.get(key);
        if (mapper == null) {
            throw new IllegalArgumentException("传入的参数有误,无法获取执行的必要条件");
        }
        //创建 Executor 对象
        Executor executor = new Executor();
        return executor.selectList(mapper, connection);
    }
}

至此自定义Mybatis已经写完

下面来测试是否正常运行

  1. 建立表
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `birthday` date NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  1. 建立实体类 User.java
public class User {
    /**
     * KEY
     */
    private Integer id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 生日
     */
    private Date birthday;
    /**
     * 性别
     */
    private String sex;
    /**
     * 通讯地址
     */
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
  1. 建立映射文件 UserDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="dao.UserDao">
   <select id="findAll" resultType="entity.User">
       select * from mybatis01.user
    </select>
</mapper>
  1. 建立接口 UserDao.java
public interface UserDao {
    /**
     * 查询所有用户
     *
     * @return
     */
    List<User> findAll();
}
  1. 测试类
public class MainTest {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> all = mapper.findAll();
        all.forEach(System.out::println);
        sqlSession.close();
        inputStream.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值