自定义持久层框架(手写mini-Mybatis)

450 阅读8分钟

一、分析 JDBC 操作问题

public static void main(String[] args) throws ClassNotFoundException, SQLException {
  Connection connection = null;
  PreparedStatement preparedStatement = null;
  ResultSet resultSet = null;
  try {
    // 加载数据库驱动
    Class.forName("com.mysql.jdbc.Driver");
    // 通过驱动管理类获取数据库链接
    connection =
      DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding = utf - 8", " root", " root");
    // 定义sql语句?表示占位符
    String sql = "select * from user where username = ?";
    // 获取预处理statement
    preparedStatement = connection.prepareStatement(sql);
    // 设置参数,第⼀个参数为sql语句中参数的序号(从1开始),第⼆个参数为设置的参数值
    preparedStatement.setString(1, "tom");
    // 向数据库发出sql执⾏查询,查询出结果集
    resultSet = preparedStatement.executeQuery();
    // 遍历查询结果集
    while (resultSet.next()) {
      int id = resultSet.getInt("id");
      String username = resultSet.getString("username");
      // 封装User
      user.setId(id);
      user.setUsername(username);
    }
    System.out.println(user);
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    // 释放资源
    if (resultSet != null) {
      try {
        resultSet.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (preparedStatement != null) {
      try {
        preparedStatement.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}
1. JDBC 问题总结:

原始jdbc开发存在的问题如下:

  1. 数据库连接创建、释放频繁造成系统资源浪费,从⽽影响系统性能。

  2. Sql语句在代码中硬编码,造成代码不易维护,实际应⽤中sql变化的可能较⼤,sql变动需要改变 java代码。

  3. 使⽤preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不⼀定,可能多也可能少,修改sql还要修改代码,系统不易维护。

  4. 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据 库记录封装成pojo对象解析⽐较⽅便

2. 问题解决思路

①使⽤数据库连接池初始化连接资源

②将sql语句抽取到xml配置⽂件中

③使⽤反射、内省等底层技术,⾃动将实体与表进⾏属性与字段的⾃动映射

3. ⾃定义框架设计
(1)使⽤端

提供核⼼配置⽂件:

sqlMapConfig.xml : 存放数据源信息,引⼊mapper.xml

Mapper.xml : sql语句的配置⽂件信息

(2)框架端
  1. 读取配置⽂件

读取完成以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可

以创建javaBean来存储

(1)Configuration : 存放数据库基本信息、Map<唯⼀标识,Mapper> 唯⼀标识:namespace + "." + id

(2)MappedStatement:sql语句、statement类型、输⼊参数java类型、输出参数java类型

  1. 解析配置⽂件

创建sqlSessionFactoryBuilder类:

⽅法:sqlSessionFactory build():

第⼀:使⽤dom4j解析配置⽂件,将解析出来的内容封装到Configuration和MappedStatement中

第⼆:创建SqlSessionFactory的实现类DefaultSqlSession

  1. 创建SqlSessionFactory:

⽅法:openSession() : 获取sqlSession接⼝的实现类实例对象

  1. 创建sqlSession接⼝及实现类:主要封装crud⽅法

⽅法:selectList(String statementId,Object param):查询所有

selectOne(String statementId,Object param):查询单个

具体实现:封装JDBC完成对数据库表的查询操作

涉及到的设计模式:

Builder构建者设计模式、⼯⼚模式、代理模式

二、⾃定义框架实现步骤

  1. 导入依赖
<dependencies>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.17</version>
  </dependency>
  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
  </dependency>
  <dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
  </dependency>
  <dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
  </dependency>
</dependencies>
  1. 创建Configuration类,用于存放DataSource和MappedStatement,供最后SQL执行取值用,所以应该在pojo包中。
  2. 同时我们还得创建一个MappedStatement类,用于存放具体SQL语句的信息,应该包含id、resultType、parameterType、sql。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MappedStatement {
    private String id;
    private String resultType;
    private String parameterType;
    private String sql;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Configuration {
    private DataSource dataSource;
    private Map<String,MappedStatement> mappedStatementMap = new HashMap<>();
}
  1. 我们先来看看最终我们要实现的效果是怎样的
// 通过一个方法将目标文件变成输入流存放在内存里面
InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
// 通过输入流获取到一个 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
// 获取到一个 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();

User user = new User();
user.setId(1);
user.setUsername("张三");

IUserDao userDao = sqlSession.getMapper(IUserDao.class);

List<User> all = userDao.findAll();
for (User user1 : all) {
  System.out.println(user1);
}
  1. 我们先来做第一步Resources.getResourceAsSteam
public class Resources {
    // 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
    public static InputStream getResourceAsSteam(String path){
        return  Resources.class.getClassLoader().getResourceAsStream(path);
    }
}
  1. 创建SqlSessionFactoryBuilder,里面有一个build方法用来返回一个SqlSessionFactory,根据开放闭合原则得先创建一个接口。
public interface SqlSessionFactory {
  // TODO
}
  1. build方法分为两步:
第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
第二:创建sqlSessionFactory对象工厂类,生产sqlSession会话对象
@Data
@AllArgsConstructor
public class SqlSessionFactoryBuilder {
    public SqlSessionFactory build(InputStream in){
        // 第一步:解析xml文件存入内存中备用
        
        // 第二步:创建sqlSessionFactory对象
        return null;
    }
}
  1. 我们创建一个新类专门用于解决解析xml文件存入内存中备用这个步骤的XMLConfigerBuilder类,内含一个parseConfig方法
public class XMLConfigBuilder {
    public Configuration parseConfig(InputStream in){
        return null;
    }
}
  1. 我们来看一下获取到的xml文件内容是什么
<configuration>
    <!--数据库配置信息-->
    <dataSource>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </dataSource>
    <!--存放mapper.xml的全路径-->
    <mapper resource="UserMapper.xml"></mapper>
</configuration>
<!--UserMapper.xml-->
<mapper namespace="com.dualseason.dao.IUserDao">

    <!--sql的唯一标识:namespace.id来组成 : statementId-->
    <select id="findAll" resultType="com.dualseason.pojo.User" >
        select * from user
    </select>
    
    <!--
        User user = new User()
        user.setId(1);
        user.setUsername("zhangsan")
    -->
    <select id="findByCondition" resultType="com.dualseason.pojo.User" paramterType="com.dualseason.pojo.User">
        select * from user where id = #{id} and username = #{username}
    </select>
</mapper>
  1. 接下来我们做的就是解析获取到的输入流形式的xml文件,代码写在XMLConfigerBuilder类中
import org.dom4j.io.SAXReader;
// 通过dom4j的SAXReader类来读取输入流获取Document对象
Document document = new SAXReader().read(in);
// 通过document获取根结点
Element rootElement = document.getRootElement();
// 获取<configuration></configuration>里面的property标签的元素,使用xpath语法进行查找,
// xpath学习地址:https://www.runoob.com/xpath/xpath-tutorial.html
List<Element> list = rootElement.selectNodes("//property");
// 使用Properties来存放<key,value>数据,也可以使用Map<key,value>替代
Properties properties = new Properties();
// 遍历<property>标签元素,将里面的属性都用<key,value>方式存入properties中
for (Element element : list) {
  String name = element.attributeValue("name");
  String value = element.attributeValue("value");
  properties.setProperty(name,value);
}
// 使用c3p0这个库的DataSource进行数据源存储
import com.mchange.v2.c3p0.ComboPooledDataSource;
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
comboPooledDataSource.setUser(properties.getProperty("username"));
comboPooledDataSource.setPassword(properties.getProperty("password"));

// 将数据源存到Configuration类里面的DataSource里面,这就得先有一个Configuration类了
configuration.setDataSource(comboPooledDataSource);

// 在XMLConfigerBuilder成员变量中添加下面代码,让该类一创建就自带一个新的Configuration类
private Configuration configuration;
public XMLConfigBuilder() {
  this.configuration = new Configuration();
}

// 对mapper.xml解析: 拿到路径 => 字节输入流 => 同上使用dom4j进行解析
// 拿到<Configuration>标签内的所有<mapper>标签,如:<mapper resource="UserMapper.xml"></mapper>
List<Element> mapperList = rootElement.selectNodes("//mapper");

for (Element element : mapperList) {
  String mapperPath = element.attributeValue("resource");
  InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
  // 这里引入一个XMLMapperBuilder类用于解析mapper.xml文件
  XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
  xmlMapperBuilder.parse(resourceAsSteam);
}

// 最后的configuration包含了
return configuration;
// 上方的new XMLMapperBuilder(configuration);传入一个configuration,所以得有构造函数
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
  this.configuration = configuration;
}
public void parse(InputStream inputStream) throws DocumentException {
  Document document = new SAXReader().read(inputStream);
  Element rootElement = document.getRootElement();
  String namespace = rootElement.attributeValue("namespace");
  List<Element> list = rootElement.selectNodes("//select");
  for (Element element : list) {
    String id = element.attributeValue("id");
    String resultType = element.attributeValue("resultType");
    String paramterType = element.attributeValue("paramterType");
    String sqlText = element.getTextTrim();
    MappedStatement mappedStatement = new MappedStatement();
    mappedStatement.setId(id);
    mappedStatement.setResultType(resultType);
    mappedStatement.setParamterType(paramterType);
    mappedStatement.setSql(sqlText);
    String key = namespace+"."+id;
    configuration.getMappedStatementMap().put(key,mappedStatement);
  }
}
// 第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中(SqlSessionFactoryBuilder类)
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
// 第二:创建sqlSessionFactory对象用于生产sqlSession会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);

SqlSessionFactory接口预留一个方法

public interface SqlSessionFactory {
    public SqlSession openSession();
}
  1. 定义DefaultSqlSessionFactory
// new DefaultSqlSessionFactory(configuration);需要传递一个configuration进来
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private Configuration configuration;
    public DefaultSqlSessionFactory(Configuration configuration) {
      this.configuration = configuration;
    }
    @Override
    public SqlSession openSession() {
      return new DefaultSqlSession(configuration);
    }
}
  1. 定义SqlSession和DefaultSqlSession
public interface SqlSession {
    //查询所有
    public <E> List<E> selectList(String statementid,Object... params) throws Exception;
    //根据条件查询单个
    public <T> T selectOne(String statementid,Object... params) throws Exception;
    //为Dao接口生成代理实现类
    public <T> T getMapper(Class<?> mapperClass);
}
public class DefaultSqlSession implements SqlSession {
  private Configuration configuration;
  public DefaultSqlSession(Configuration configuration) {
    this.configuration = configuration;
  }
}
  1. 定义一个Executor接口
public interface Executor {
  // 传入Configuration,MappedStatement,传过来的实体类(例如user)
  public <E> List<E> query(Configuration configuration,MappedStatement mappedStatement,Object... params) throws Exception;
}
  1. 定义工具类BoundSql
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BoundSql {
		//解析过后的sql
    private String sqlText; 
    private List<ParameterMapping> parameterMappingList = new ArrayList<>();
}
  1. 创建GenericTokenParser解析类
public class GenericTokenParser {

  private final String openToken; //开始标记
  private final String closeToken; //结束标记
  private final TokenHandler handler; //标记处理器

  public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
    this.openToken = openToken;
    this.closeToken = closeToken;
    this.handler = handler;
  }

  /**
   * 解析${}和#{}
   * @param text
   * @return
   * 该方法主要实现了配置文件、脚本等片段中占位符的解析、处理工作,并返回最终需要的数据。
   * 其中,解析工作由该方法完成,处理工作是由处理器handler的handleToken()方法来实现
   */
  public String parse(String text) {
    // 验证参数问题,如果是null,就返回空字符串。
    if (text == null || text.isEmpty()) {
      return "";
    }

    // 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
    int start = text.indexOf(openToken, 0);
    if (start == -1) {
      return text;
    }

   // 把text转成字符数组src,并且定义默认偏移量offset=0、存储最终需要返回字符串的变量builder,
    // text变量中占位符对应的变量名expression。判断start是否大于-1(即text中是否存在openToken),如果存在就执行下面代码
    char[] src = text.toCharArray();
    int offset = 0;
    final StringBuilder builder = new StringBuilder();
    StringBuilder expression = null;
    while (start > -1) {
     // 判断如果开始标记前如果有转义字符,就不作为openToken进行处理,否则继续处理
      if (start > 0 && src[start - 1] == '\\') {
        builder.append(src, offset, start - offset - 1).append(openToken);
        offset = start + openToken.length();
      } else {
        //重置expression变量,避免空指针或者老数据干扰。
        if (expression == null) {
          expression = new StringBuilder();
        } else {
          expression.setLength(0);
        }
        builder.append(src, offset, start - offset);
        offset = start + openToken.length();
        int end = text.indexOf(closeToken, offset);
        while (end > -1) {////存在结束标记时
          if (end > offset && src[end - 1] == '\\') {//如果结束标记前面有转义字符时
            // this close token is escaped. remove the backslash and continue.
            expression.append(src, offset, end - offset - 1).append(closeToken);
            offset = end + closeToken.length();
            end = text.indexOf(closeToken, offset);
          } else {//不存在转义字符,即需要作为参数进行处理
            expression.append(src, offset, end - offset);
            offset = end + closeToken.length();
            break;
          }
        }
        if (end == -1) {
          // close token was not found.
          builder.append(src, start, src.length - start);
          offset = src.length;
        } else {
          //首先根据参数的key(即expression)进行参数处理,返回?作为占位符
          builder.append(handler.handleToken(expression.toString()));
          offset = end + closeToken.length();
        }
      }
      start = text.indexOf(openToken, offset);
    }
    if (offset < src.length) {
      builder.append(src, offset, src.length - offset);
    }
    return builder.toString();
  }
}
  1. 创建ParameterMapping类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ParameterMapping {
    private String content;
}
  1. 创建TokenHandler
public interface TokenHandler {
  String handleToken(String content);
}
  1. 创建ParameterMappingTokenHandler实现TokenHandler接口
public class ParameterMappingTokenHandler implements TokenHandler {
	private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();

	// context是参数名称 #{id} #{username}

	public String handleToken(String content) {
		parameterMappings.add(buildParameterMapping(content));
		return "?";
	}

	private ParameterMapping buildParameterMapping(String content) {
		ParameterMapping parameterMapping = new ParameterMapping(content);
		return parameterMapping;
	}

	public List<ParameterMapping> getParameterMappings() {
		return parameterMappings;
	}

	public void setParameterMappings(List<ParameterMapping> parameterMappings) {
		this.parameterMappings = parameterMappings;
	}
}
  1. 实现Executor
@Override
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
  // 1. 注册驱动,获取连接
  Connection connection = configuration.getDataSource().getConnection();

  // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
  // 转换sql语句: select * from user where id = ? and username = ? ,转换的过程中,还需要对#{}里面的值进行解析存储
  String sql = mappedStatement.getSql();
  BoundSql boundSql = getBoundSql(sql);

  // 3.获取预处理对象:preparedStatement
  PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

  // 4. 设置参数
  //获取到了参数的全路径
  String paramterType = mappedStatement.getParamterType();
  Class<?> paramtertypeClass = getClassType(paramterType);

  List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
  for (int i = 0; i < parameterMappingList.size(); i++) {
    ParameterMapping parameterMapping = parameterMappingList.get(i);
    String content = parameterMapping.getContent();

    //反射
    Field declaredField = paramtertypeClass.getDeclaredField(content);
    //暴力访问
    declaredField.setAccessible(true);
    Object o = declaredField.get(params[0]);

    preparedStatement.setObject(i + 1, o);

  }

  // 5. 执行sql
  ResultSet resultSet = preparedStatement.executeQuery();
  String resultType = mappedStatement.getResultType();
  Class<?> resultTypeClass = getClassType(resultType);

  ArrayList<Object> objects = new ArrayList<>();

  // 6. 封装返回结果集
  while (resultSet.next()) {
    Object o = resultTypeClass.newInstance();
    //元数据
    ResultSetMetaData metaData = resultSet.getMetaData();
    for (int i = 1; i <= metaData.getColumnCount(); i++) {

      // 字段名
      String columnName = metaData.getColumnName(i);
      // 字段的值
      Object value = resultSet.getObject(columnName);

      //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
      PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
      Method writeMethod = propertyDescriptor.getWriteMethod();
      writeMethod.invoke(o, value);
    }
    objects.add(o);
  }
  return (List<E>) objects;

}
  1. 实现DefaultSqlSession
@Override
public <E> List<E> selectList(String statementid, Object... params) throws Exception {
  //将要去完成对simpleExecutor里的query方法的调用
  simpleExecutor simpleExecutor = new simpleExecutor();
  MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
  List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
  return (List<E>) list;
}
@Override
public <T> T selectOne(String statementid, Object... params) throws Exception {
  List<Object> objects = selectList(statementid, params);
  if(objects.size()==1){
    return (T) objects.get(0);
  }else {
    throw new RuntimeException("查询结果为空或者返回结果过多");
  }
}
@Override
public <T> T getMapper(Class<?> mapperClass) {
  // 使用JDK动态代理来为Dao接口生成代理对象,并返回
  Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      // 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
      // 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
      // 方法名:findAll
      String methodName = method.getName();
      String className = method.getDeclaringClass().getName();

      String statementId = className+"."+methodName;

      // 准备参数2:params:args
      // 获取被调用方法的返回值类型
      Type genericReturnType = method.getGenericReturnType();
      // 判断是否进行了 泛型类型参数化
      if(genericReturnType instanceof ParameterizedType){
        List<Object> objects = selectList(statementId, args);
        return objects;
      }
      return selectOne(statementId,args);
    }
  });
  return (T) proxyInstance;
}