自定义持久层框架设计思路:

使用端:(项目) 引入持久层框架(jar包)

提供两部分配置信息:数据库配置信息,sql配置信息:SQL语句、参数类型、返回值类型 使用配置文件来提供:

1、 SqlMapConfig.xml:存放数据库配置,存放mapper.xml全路径 (存放mapper.xml全路径只要是为了值传递一个path)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <dataSource>
      <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
      <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/zdy_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"></property>
      <property name="username" value="root"></property>
      <property name="password" value="root"></property>
  </dataSource>

  <mapper resource="UserMapper.xml"></mapper>

</configuration>

2、 mapper.xml:存放sql配置信息

<?xml version="1.0" encoding="utf-8"?>
<mapper namespace="com.jdbc_test.dao.IUserDao">
  <select id="findAll" resultType="com.jdbc_test.pojo.User">
      select * from user
  </select>
  <select id="findByConditions" resultType="com.jdbc_test.pojo.User" paramType="com.jdbc_test.pojo.User">
      select * from user where id = #{id} and username = #{username}
  </select>
</mapper>

自定义持久层框架:本质就是对jdbc进行封装

1、 加载配置文件:根据路径,加载为字节输入流,存在内存中

创建Resource类 方法:InputStream getResourceAsStream(String path)

public class Resource {
  public static InputStream getResourceAsStream(String path) {
      return Resource.class.getClassLoader().getResourceAsStream(path);
  }
}

2、 创建两个JavaBean (容器对象) 用来存储对配置文件解析出来的内容

(1)Configuration:核心配置类,存放sqlMapConfig.xml中的数据库基本信息,Map<唯一标识, Mapper> 唯一标识: namespace.id
public class Configuration {

  private DataSource dataSource;

  Map<String, MappedStatement> map = new HashMap<String, MappedStatement>();

  public DataSource getDataSource() {
      return dataSource;
  }

  public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
  }

  public Map<String, MappedStatement> getMap() {
      return map;
  }

  public void setMap(Map<String, MappedStatement> map) {
      this.map = map;
  }
}
(2)MappedStatement:映射配置类,存放mapper.xml中解析出来的SQL语句、id、参数类型、返回值类型、statement类型
public class MappedStatement {

  private String id;
  private String paramterType;
  private String resultType;
  private String sql;

  public String getId() {
      return id;
  }

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

  public String getParamterType() {
      return paramterType;
  }

  public void setParamterType(String paramterType) {
      this.paramterType = paramterType;
  }

  public String getResultType() {
      return resultType;
  }

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

  public String getSql() {
      return sql;
  }

  public void setSql(String sql) {
      this.sql = sql;
  }
}

3、 解析配置文件: dom4j

创建类:SQLSessionFactoryBuilder: build(InputStream in);

(1) 使用dom4j解析配置文件,将解析出来的内容封装到容器对象
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parse(InputStream in) throws DocumentException, PropertyVetoException, NamingException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        //解析configuration
        Element configurationElement = document.getRootElement();
        List<Element> propertyList = configurationElement.selectNodes("//property");

        Properties properties = new Properties();
        for (Element element : propertyList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        this.configuration.setDataSource(comboPooledDataSource);

        //解析mapper
        List<Element> mapperList = configurationElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperFilePath = element.attributeValue("resource");
            InputStream resourceAsStream = Resource.getResourceAsStream(mapperFilePath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(this.configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return this.configuration;
    }
}
public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        //解析mappedStatement  <mapper namespace="user">
        Element mappedStatementElement = document.getRootElement();
        String namespace = mappedStatementElement.attributeValue("namespace");

        List<Element> selectList = mappedStatementElement.selectNodes("//select");
        for (Element element : selectList) {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramType = element.attributeValue("paramType");
            String sql = element.getTextTrim();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            this.configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
(2) 创建SQLSessionFactory对象,生产SQLSession: 会话对象(工厂模式)
public class SqlSessionFactoryBuilder {

    public SqlSessionFactory build(InputStream in) throws Exception {
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.parse(in);
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        return sqlSessionFactory;

    }
}

4、 创建SQLSessionFactory接口及实现类DefaultSQLSessionFactory

openSession(): 生产SqlSession

public interface SqlSessionFactory {
    SqlSession openSession();
}
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    public SqlSession openSession() {
        return new DefaultSqlSession(this.configuration);
    }
}

5、 创建SqlSession接口及实现类DefaultSqlSession

定义对数据库的crud操作:
	insert()
	selectList()
	selectOne()
	update()
	delete()
public interface SqlSession {
    <E> List<E> selectList(String statementId, Object...param) throws Exception;
    <T> T selectOne(String statementId, Object...param) throws Exception;
    //为Dao接口生成代理实现类
    public <T> T getMapper(Class<?> mapperClass);
}
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object...params) throws Exception {
        SampleExecutor sampleExecutor = new SampleExecutor();

        List<E> result = sampleExecutor.query(this.configuration, this.configuration.getMappedStatementMap().get(statementId), params);

        return result;
    }

    @Override
    public <T> T selectOne(String statementId, Object...params) throws Exception {
        List<Object> objects = this.selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者多个");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object instance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                String name = method.getDeclaringClass().getName();
                Type genericReturnType = method.getGenericReturnType();
                //genericReturnType instanceof ParameterizedType 返回值类型是个列表
                if (genericReturnType instanceof ParameterizedType) {
                    return  selectList(name+"."+methodName, args);
                }
                return selectOne(name+"."+methodName, args);
            }
        });
        return (T) instance;
    }
}

6、 创建Executor接口及实现类SimpleExecutor

query(Configuration, MappedStatement, Object...params)  执行的就是jdbc代码
public interface Executor {
    <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object...params) throws Exception;
}
public class SampleExecutor implements Executor {

    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        // 1. 获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取boundSql
        BoundSql boundSql = this.getBoundSql(mappedStatement);

        // 3. 预处理对象
        PreparedStatement ps = connection.prepareStatement(boundSql.getSql());

        // 4. 设置参数
        String paramterType = mappedStatement.getParamterType();
        Class paramterClazz = getClassType(paramterType);

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

            //通过字段名称  在param中获取字段的值
            Field declaredField = paramterClazz.getDeclaredField(content);
            //设置暴力访问
            declaredField.setAccessible(true);
            //字段对应的值
            Object o = declaredField.get(params[0]);

            //设置对应位置‘?’占位符的参数
            ps.setObject(i + 1, o);
        }
        // 5. 执行sql
        ResultSet resultSet = ps.executeQuery();

        // 6. 封装返回结果
        String resultType = mappedStatement.getResultType();
        Class resultClazz = this.getClassType(resultType);
        //用来保存结果集
        List<Object> list = new ArrayList<Object>();

        while (resultSet.next()) {
            Object instance = resultClazz.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object result = resultSet.getObject(columnName);

                //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClazz);
                propertyDescriptor.getWriteMethod().invoke(instance, result);
            }
            list.add(instance);
        }

        return (List<E>) list;
    }

    private Class getClassType(String paramterType) throws ClassNotFoundException {
        if (null != paramterType) {
            Class<?> clazz = Class.forName(paramterType);
            return clazz;
        }
        return null;
    }

    private BoundSql getBoundSql(MappedStatement mappedStatement) {

        // 1. 获取sql   带占位符的
        String sql = mappedStatement.getSql();
        // 2. 解析sql
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        return new BoundSql(parseSql, parameterMappingTokenHandler.getParameterMappings());
    }
}

7、 编写测试类,测试代码

public class IPersistenceTest {

    @Test
    public void test1() throws Exception {
        InputStream resourceAsStream = Resource.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        List<User> userList = sqlSession.selectList("user.selectList");
//        userList.forEach(user -> {
//            System.out.println(user);
//        });
        User user = new User();
        user.setId(1);
        user.setUsername("lucy");
        User o = sqlSession.selectOne("user.selectOne", user);
        System.out.println(o);
    }


    @Test
    public void test2() throws Exception {

        IUserDaoImpl iUserDao = new IUserDaoImpl();
        List<User> all = iUserDao.findAll();
        all.forEach(user -> {
            System.out.println(user);
        });
    }

    @Test
    public void test3() throws Exception {
        InputStream resourceAsStream = Resource.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        List<User> all = mapper.findAll();
        all.forEach(user -> {
            System.out.println(user);
        });
    }
}

8、 过程中文件

BoundSql

public class BoundSql {

    private String sql;

    private List<ParameterMapping> parameterMappingList;

    public BoundSql(String sql, List<ParameterMapping> parameterMappingList) {
        this.sql = sql;
        this.parameterMappingList = parameterMappingList;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public List<ParameterMapping> getParameterMappingList() {
        return parameterMappingList;
    }

    public void setParameterMappingList(List<ParameterMapping> parameterMappingList) {
        this.parameterMappingList = parameterMappingList;
    }
}

User

public class User {
    private int id;
    private String username;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}';
    }
}

IUserDaoImpl

public class IUserDaoImpl implements IUserDao {
    @Override
    public List<User> findAll() throws Exception {
        InputStream resourceAsStream = Resource.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> userList = sqlSession.selectList("user.selectList");
        return userList;
    }

    @Override
    public User findByConditions(User user) throws Exception {
        InputStream resourceAsStream = Resource.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        user.setId(1);
        user.setUsername("lucy");
        User o = sqlSession.selectOne("user.selectOne", user);
        System.out.println(o);
        return o;
    }
}

user.sql

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8