Java精进-手写持久层框架

锦通  金牌会员 | 2022-9-16 17:20:13 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 554|帖子 554|积分 1662

前言

本文适合有一定java基础的同学,通过自定义持久层框架,可以更加清楚常用的mybatis等开源框架的原理。
JDBC操作回顾及问题分析

学习java的同学一定避免不了接触过jdbc,让我们来回顾下初学时期接触的jdbc操作吧
以下代码连接数据库查询用户表信息,用户表字段分别为用户id,用户名username。
  1. Connection connection = null;
  2.         PreparedStatement preparedStatement = null;
  3.         ResultSet resultSet = null;
  4.         User user = new User();
  5.         try {
  6.             // 加载数据库驱动
  7.             //Class.forName("com.mysql.jdbc.Driver");
  8.             Class.forName("com.mysql.cj.jdbc.Driver");
  9.             // 通过驱动管理类获取数据库链接
  10.             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mimashi3124");
  11.             // 定义sql语句?表示占位符
  12.             String sql = "select * from user where username = ?";
  13.             // 获取预处理statement
  14.             preparedStatement = connection.prepareStatement(sql);
  15.             // 设置参数,第⼀个参数为sql语句中参数的序号(从1开始),第⼆个参数为设置的参数值
  16.             preparedStatement.setString(1, "盖伦");
  17.             // 向数据库发出sql执⾏查询,查询出结果集
  18.             resultSet = preparedStatement.executeQuery();
  19.             // 遍历查询结果集
  20.             while (resultSet.next()) {
  21.                 int id = resultSet.getInt("id");
  22.                 String username = resultSet.getString("username");
  23.                 // 封装User
  24.                 user.setId(id);
  25.                 user.setUsername(username);
  26.             }
  27.             System.out.println(user);
  28.         } catch (
  29.                 Exception e) {
  30.             e.printStackTrace();
  31.         } finally {
  32.             // 释放资源
  33.             if (resultSet != null) {
  34.                 try {
  35.                     resultSet.close();
  36.                 } catch (SQLException e) {
  37.                     e.printStackTrace();
  38.                 }
  39.             }
  40.             if (preparedStatement != null) {
  41.                 try {
  42.                     preparedStatement.close();
  43.                 } catch (SQLException e) {
  44.                     e.printStackTrace();
  45.                 }
  46.             }
  47.             if (connection != null) {
  48.                 try {
  49.                     connection.close();
  50.                 } catch (SQLException e) {
  51.                     e.printStackTrace();
  52.                 }
  53.             }
  54.         }
复制代码
查看代码我们可以发现使用JDBC操作数据库存在以下问题:

  • 数据库连接创建、释放频繁造成系统资源浪费,从⽽影响系统性能。
  • Sql语句我们是写在代码里的,代码不容易维护,实际应⽤中sql变化的可能较⼤,sql变动需要改变 java代码。
  • 使⽤preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不⼀定,可能多也可能少,修改sql还要修改代码,系统不易维护。
  • 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据 库记录封装成pojo对象解析⽐较⽅便
问题解决思路

  • 使⽤数据库连接池初始化连接资源,避免资源浪费
  • 将sql语句抽取到xml配置中,这种sql的变动只用关注xml文件,不比去一堆java代码里改写sql
  • 参数硬编码问题可以使用反射、内省等技术、自动将实体与表字段进行映射。
自己动手写个持久层框架

接下来,我们来一个个解决上面的问题
数据库连接池我们可以直接使用c3p0提供的ComboPooledDataSource即可
为了解决sql硬编码问题,我们要把sql写到xml文件中,那自然是要定义一个xml文件了。
光有sql肯定不行,毕竟我们要先连接数据库,sql语句才有存在的意义。所以xml中得先定义数据配置信息,然后才是sql语句。
1.定义配置xml文件

我们新建一个sqlMapConfig.xml,定义数据源信息、并且增加两个sql语句,parameterType为sql执行参数,resultType为方法返回实体。
代码如下(数据库不同版本使用驱动类可能不同):
  1. <configuration>
  2.    
  3.     <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
  4.     <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai"/>
  5.     <property name="username" value="root"/>
  6.     <property name="password" value="mimashi3124"/>
  7.         <select id="selectOne" parameterType="org.example.pojo.User"
  8.             resultType="org.example.pojo.User">
  9.         select * from user where id = #{id} and username =#{username}
  10.     </select>
  11.     <select id="selectList" resultType="org.example.pojo.User">
  12.         select * from user
  13.     </select>
  14. </configuration>
复制代码
现在xml文件数据库信息也有了,sql语句定义也有了,还有什么问题呢?
我们实际中对sql的操作会涉及到不同的表,所以我们改进一下,把每个表的sql语句单独放在一个xml里,这样结构更清晰就容易维护。
优化以后的xml配置现在是这样了
sqlMapConfig.xml
  1. <configuration>
  2.    
  3.     <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
  4.        
  5.     <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai"/>
  6.     <property name="username" value="root"/>
  7.     <property name="password" value="mimashi3124"/>
  8.    
  9.         <mapper resource="mapper.xml"></mapper>
  10. </configuration>
复制代码
mapper.xml
  1. <mapper namespace="user">
  2.     <select id="selectOne" parameterType="org.example.pojo.User"
  3.             resultType="org.example.pojo.User">
  4.         select * from user where id = #{id} and username =#{username}
  5.     </select>
  6.     <select id="selectList" resultType="org.example.pojo.User">
  7.         select * from user
  8.     </select>
  9. </mapper>
复制代码
顺便定义一下业务实体User
  1. public class User {
  2.     private int id;
  3.     private String username;
  4.    
  5.     public int getId() {
  6.         return id;
  7.     }
  8.     public void setId(int id) {
  9.         this.id = id;
  10.     }
  11.     public String getUsername() {
  12.         return username;
  13.     }
  14.     public void setUsername(String username) {
  15.         this.username = username;
  16.     }
  17.     @Override
  18.     public String toString() {
  19.         return "User{" +
  20.                 "id=" + id +
  21.                 ", username='" + username + '\'' +
  22.                 '}';
  23.     }
  24. }
复制代码
2.读取配置文件

读取完成以后以流的形式存在,不好操作,所以我们要做解析拿到信息,创建实体对象来存储。

  • Configuration : 存放数据库基本信息、Map 唯⼀标识:namespace + "." + id
  • MappedStatement:存放sql语句、输⼊参数类型、输出参数类型
xml解析我们使用dom4j
首先引入maven依赖
代码如下(mysql驱动版本根据实际使用mysql版本调整):
  1. <properties>
  2.         <maven.compiler.source>8</maven.compiler.source>
  3.         <maven.compiler.target>8</maven.compiler.target>
  4.     </properties>
  5.     <dependencies>
  6.         <dependency>
  7.             <groupId>mysql</groupId>
  8.             <artifactId>mysql-connector-java</artifactId>
  9.             <version>8.0.22</version>
  10.         </dependency>
  11.         <dependency>
  12.             <groupId>c3p0</groupId>
  13.             <artifactId>c3p0</artifactId>
  14.             <version>0.9.1.2</version>
  15.         </dependency>
  16.         <dependency>
  17.             <groupId>log4j</groupId>
  18.             <artifactId>log4j</artifactId>
  19.             <version>1.2.12</version>
  20.         </dependency>
  21.         <dependency>
  22.             <groupId>junit</groupId>
  23.             <artifactId>junit</artifactId>
  24.             <version>4.10</version>
  25.         </dependency>
  26.         <dependency>
  27.             <groupId>dom4j</groupId>
  28.             <artifactId>dom4j</artifactId>
  29.             <version>1.6.1</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>jaxen</groupId>
  33.             <artifactId>jaxen</artifactId>
  34.             <version>1.1.6</version>
  35.         </dependency>
  36.     </dependencies>
复制代码
数据库配置实体 Configuration
  1. public class Configuration {
  2.     //数据源
  3.     private DataSource dataSource;
  4.     //map集合: key:statementId value:MappedStatement
  5.     private Map<String,MappedStatement> mappedStatementMap = new HashMap<>();
  6.     public DataSource getDataSource() {
  7.         return dataSource;
  8.     }
  9.     public Configuration setDataSource(DataSource dataSource) {
  10.         this.dataSource = dataSource;
  11.         return this;
  12.     }
  13.     public Map<String, MappedStatement> getMappedStatementMap() {
  14.         return mappedStatementMap;
  15.     }
  16.     public Configuration setMappedStatementMap(Map<String, MappedStatement> mappedStatementMap) {
  17.         this.mappedStatementMap = mappedStatementMap;
  18.         return this;
  19.     }
  20. }
复制代码
Sql语句信息实体
  1. public class MappedStatement {
  2.     //id
  3.     private String id;
  4.     //sql语句
  5.     private String sql;
  6.     //输⼊参数
  7.     private String parameterType;
  8.     //输出参数
  9.     private String resultType;
  10.     public String getId() {
  11.         return id;
  12.     }
  13.     public MappedStatement setId(String id) {
  14.         this.id = id;
  15.         return this;
  16.     }
  17.     public String getSql() {
  18.         return sql;
  19.     }
  20.     public MappedStatement setSql(String sql) {
  21.         this.sql = sql;
  22.         return this;
  23.     }
  24.     public String getParameterType() {
  25.         return parameterType;
  26.     }
  27.     public MappedStatement setParameterType(String parameterType) {
  28.         this.parameterType = parameterType;
  29.         return this;
  30.     }
  31.     public String getResultType() {
  32.         return resultType;
  33.     }
  34.     public MappedStatement setResultType(String resultType) {
  35.         this.resultType = resultType;
  36.         return this;
  37.     }
  38. }
复制代码
顺便定义一个Resources类来读取xml文件流
  1. public class Resources {
  2.     public static InputStream getResourceAsSteam(String path) {
  3.         return Resources.class.getClassLoader().getResourceAsStream(path);
  4.     }
  5. }
复制代码
接下来就是实际的解析了,因为解析代码比较多,我们考虑封装类单独处理解析
定义XMLConfigBuilder类解析数据库配置信息
  1. public class XMLConfigBuilder {
  2.     private Configuration configuration;
  3.     public XMLConfigBuilder() {
  4.         this.configuration = new Configuration();
  5.     }
  6.     public Configuration parserConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
  7.         Document document = new SAXReader().read(inputStream);
  8.         Element rootElement = document.getRootElement();
  9.         List<Element> propertyElements = rootElement.selectNodes("//property");
  10.         Properties properties = new Properties();
  11.         for (Element propertyElement : propertyElements) {
  12.             String name = propertyElement.attributeValue("name");
  13.             String value = propertyElement.attributeValue("value");
  14.             properties.setProperty(name,value);
  15.         }
  16.         //解析到数据库配置信息,设置数据源信息
  17.         ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  18.         comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
  19.         comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
  20.         comboPooledDataSource.setUser(properties.getProperty("username"));
  21.         comboPooledDataSource.setPassword(properties.getProperty("password"));
  22.                
  23.         configuration.setDataSource(comboPooledDataSource);
  24.                 //将configuration传入XMLMapperBuilder中做sql语句解析。
  25.         XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(this.configuration);
  26.         List<Element> mapperElements = rootElement.selectNodes("//mapper");
  27.         for (Element mapperElement : mapperElements) {
  28.             String mapperPath = mapperElement.attributeValue("resource");
  29.             InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(mapperPath);
  30.             xmlMapperBuilder.parse(resourceAsStream);
  31.         }
  32.         return configuration;
  33.     }
  34. }
复制代码
定义XMLMapperBuilder类解析数据库配置信息
  1. public class XMLMapperBuilder {
  2.     private Configuration configuration;
  3.     public XMLMapperBuilder(Configuration configuration) {
  4.         this.configuration = configuration;
  5.     }
  6.     public void parse(InputStream inputStream) throws DocumentException,
  7.             ClassNotFoundException {
  8.         Document document = new SAXReader().read(inputStream);
  9.         Element rootElement = document.getRootElement();
  10.         String namespace = rootElement.attributeValue("namespace");
  11.         List<Element> select = rootElement.selectNodes("select");
  12.         for (Element element : select) { //id的值
  13.             String id = element.attributeValue("id");
  14.             String parameterType = element.attributeValue("parameterType"); //输⼊参数
  15.             String resultType = element.attributeValue("resultType"); //返回参数
  16.             //statementId,后续调用通过statementId,找到对应的sql执行
  17.             String key = namespace + "." + id;
  18.             //sql语句
  19.             String textTrim = element.getTextTrim();
  20.             //封装 mappedStatement
  21.             MappedStatement mappedStatement = new MappedStatement();
  22.             mappedStatement.setId(id);
  23.             mappedStatement.setParameterType(parameterType);
  24.             mappedStatement.setResultType(resultType);
  25.             mappedStatement.setSql(textTrim);
  26.             //填充 configuration
  27.             configuration.getMappedStatementMap().put(key, mappedStatement);
  28.         }
  29.     }
  30. }
复制代码
现在我们可以通过调用配置解析的方法拿到Configuration对象了。但是我们实际使用,肯定是希望我给你配置信息、sql语句,再调用你的方法就返回结果了。
所以我们还需要定义一个数据库操作接口(类)
3.定义sql操作接口SqlSession
  1. public interface SqlSession {
  2.         //查询多个
  3.     public <E> List<E> selectList(String statementId, Object... param) throws Exception;
  4.         //查询一个
  5.     public <T> T selectOne(String statementId,Object... params) throws Exception;
  6. }
复制代码
对操作接口SqlSession做具体实现,这里主要是通过statementId找到对应的sql信息,进行执行
代码中simpleExcutor做真正的数据库语句执行、返回参数封装等操作
  1. public class DefaultSqlSession implements SqlSession {
  2.     private Configuration configuration;
  3.     private Executor simpleExcutor = new SimpleExecutor();
  4.     public DefaultSqlSession(Configuration configuration) {
  5.         this.configuration = configuration;
  6.     }
  7.     @Override
  8.     public <E> List<E> selectList(String statementId, Object... param) throws Exception {
  9.         MappedStatement mappedStatement =
  10.                 configuration.getMappedStatementMap().get(statementId);
  11.         List<E> query = simpleExcutor.query(configuration, mappedStatement, param);
  12.         return query;
  13.     }
  14.     @Override
  15.     public <T> T selectOne(String statementId, Object... params) throws Exception {
  16.         List<Object> objects = selectList(statementId, params);
  17.         if (objects.size() == 1) {
  18.             return (T) objects.get(0);
  19.         } else {
  20.             throw new RuntimeException("返回结果过多");
  21.         }
  22.     }
  23. }
复制代码
4.编写数据库执行逻辑

数据库操作类DefaultSqlSession中的selectList方法调用到了simpleExcutor.query()方法
  1. public class SimpleExecutor implements Executor {
  2.     private Connection connection = null;
  3.     @Override
  4.     public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
  5.         //获取连接
  6.         connection = configuration.getDataSource().getConnection();
  7.         // select * from user where id = #{id} and username = #{username} String sql =
  8.         String sql = mappedStatement.getSql();
  9.         //对sql进⾏处理
  10.         BoundSql boundSql = getBoundSql(sql);
  11.         // 3.获取预处理对象:preparedStatement
  12.         PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
  13.         // 4. 设置参数
  14.         //获取到了参数的全路径
  15.         String parameterType = mappedStatement.getParameterType();
  16.         Class<?> parameterTypeClass = getClassType(parameterType);
  17.         List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
  18.         for (int i = 0; i < parameterMappingList.size(); i++) {
  19.             ParameterMapping parameterMapping = parameterMappingList.get(i);
  20.             String content = parameterMapping.getContent();
  21.             //反射
  22.             Field declaredField = parameterTypeClass.getDeclaredField(content);
  23.             //暴力访问
  24.             declaredField.setAccessible(true);
  25.             Object o = declaredField.get(params[0]);
  26.             preparedStatement.setObject(i+1,o);
  27.         }
  28.         // 5. 执行sql
  29.         ResultSet resultSet = preparedStatement.executeQuery();
  30.         String resultType = mappedStatement.getResultType();
  31.         Class<?> resultTypeClass = getClassType(resultType);
  32.         ArrayList<Object> objects = new ArrayList<>();
  33.         // 6. 封装返回结果集
  34.         while (resultSet.next()){
  35.             Object o =resultTypeClass.newInstance();
  36.             //元数据
  37.             ResultSetMetaData metaData = resultSet.getMetaData();
  38.             for (int i = 1; i <= metaData.getColumnCount(); i++) {
  39.                 // 字段名
  40.                 String columnName = metaData.getColumnName(i);
  41.                 // 字段的值
  42.                 Object value = resultSet.getObject(columnName);
  43.                 //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
  44.                 PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
  45.                 Method writeMethod = propertyDescriptor.getWriteMethod();
  46.                 writeMethod.invoke(o,value);
  47.             }
  48.             objects.add(o);
  49.         }
  50.         return (List<E>) objects;
  51.     }
  52.     @Override
  53.     public void close() throws SQLException {
  54.     }
  55.     private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
  56.         if(parameterType!=null){
  57.             Class<?> aClass = Class.forName(parameterType);
  58.             return aClass;
  59.         }
  60.         return null;
  61.     }
  62.     private BoundSql getBoundSql(String sql) {
  63.         //标记处理类:主要是配合通⽤标记解析器GenericTokenParser类完成对配置⽂件等的解 析⼯作,其中
  64.         //TokenHandler主要完成处理
  65.         ParameterMappingTokenHandler parameterMappingTokenHandler = new
  66.                 ParameterMappingTokenHandler();
  67.         //GenericTokenParser :通⽤的标记解析器,完成了代码⽚段中的占位符的解析,然后再根 据给定的
  68.        // 标记处理器(TokenHandler)来进⾏表达式的处理
  69.         //三个参数:分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处 理器)
  70.         GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}",
  71.                 parameterMappingTokenHandler);
  72.         String parse = genericTokenParser.parse(sql);
  73.         List<ParameterMapping> parameterMappings =
  74.                 parameterMappingTokenHandler.getParameterMappings();
  75.         return new BoundSql(parse, parameterMappings);
  76.     }
  77. }
复制代码
上面的注释比较详细,流程为

  • 根据对应的statementId获取到要执行的sql语句、调用参数、返回参数。
  • 对sql的占位符进行解析、调用参数进行设置
  • 根据解析到的入参字段,通过反射获取到对应的值,进行sql语句参数设定
  • 执行sql语句,使用反射、内省,根据数据库表和实体的对应关系,完成对象属性的设置,最终返回结果。
通过以上步骤,我们获取到了数据库配置、sql语句信息。定义了数据库操作类SqlSession,但是我们并没有在什么地方调用解析配置文件。
我们还需要一个东西把两者给串起来,这里我们可以使用工厂模式来生成SqlSession
使用工厂模式创建SqlSession
  1. public interface SqlSessionFactory {
  2.     public SqlSession openSession();
  3. }
复制代码
  1. public class DefaultSqlSessionFactory implements SqlSessionFactory{
  2.     private Configuration configuration;
  3.     public DefaultSqlSessionFactory(Configuration configuration) {
  4.         this.configuration = configuration;
  5.     }
  6.     @Override
  7.     public SqlSession openSession() {
  8.         return new DefaultSqlSession(configuration);
  9.     }
  10. }
复制代码
同时为了屏蔽构建SqlSessionFactory工厂类时获取Configuration的解析过程,我们可以使用构建者模式来获得一个SqlSessionFactory类。
  1. public class SqlSessionFactoryBuilder {
  2.     public SqlSessionFactory build(InputStream inputStream) throws PropertyVetoException, DocumentException, ClassNotFoundException {
  3.         XMLConfigBuilder xmlConfigerBuilder = new XMLConfigBuilder();
  4.         Configuration configuration = xmlConfigerBuilder.parserConfiguration(inputStream);
  5.         SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
  6.         return sqlSessionFactory;
  7.     }
  8. }
复制代码
5.调用测试

终于好了,通过以上几个步骤我们现在可以具体调用执行代码了。
  1. public static void main(String[] args) throws Exception {
  2.         InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
  3.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
  4.         SqlSession sqlSession = sqlSessionFactory.openSession();
  5.         User user = new User();
  6.         user.setId(1);
  7.         user.setUsername("盖伦");
  8.         User user2 = sqlSession.selectOne("user.selectOne", user);
  9.         System.out.println(user2);
  10.         List<User> users = sqlSession.selectList("user.selectList");
  11.         for (User user1 : users) {
  12.             System.out.println(user1);
  13.         }
  14.     }
复制代码
代码正确执行,输出

⾃定义框架优化

上述⾃定义框架,解决了JDBC操作数据库带来的⼀些问题:例如频繁创建释放数据库连接,硬编
码,⼿动封装返回结果集等问题,现在我们继续来分析刚刚完成的⾃定义框架代码,有没有什么问题呢?
问题如下:

  • dao的实现类中存在重复的代码,整个操作的过程模板重复(创建sqlsession,调⽤sqlsession⽅ 法,关闭sqlsession)
  • dao的实现类中存在硬编码,调⽤sqlsession的⽅法时,参数statement的id硬编码
我们可以使用代理模式,生成代理对象,在调用之前获取到执行方法的方法名、具体类。这样我们就能获取到statementId。
为SqlSession类新增getMappper方法,获取代理对象
  1. public interface SqlSession {
  2.     public <E> List<E> selectList(String statementId, Object... param) throws Exception;
  3.     public <T> T selectOne(String statementId,Object... params) throws Exception;
  4.     //为Dao接口生成代理实现类
  5.     public <T> T getMapper(Class<?> mapperClass);
  6. }
复制代码
  1. public class DefaultSqlSession implements SqlSession {
  2.     private Configuration configuration;
  3.     private Executor simpleExcutor = new SimpleExecutor();
  4.     public DefaultSqlSession(Configuration configuration) {
  5.         this.configuration = configuration;
  6.     }
  7.     @Override
  8.     public <E> List<E> selectList(String statementId, Object... param) throws Exception {
  9.         MappedStatement mappedStatement =
  10.                 configuration.getMappedStatementMap().get(statementId);
  11.         List<E> query = simpleExcutor.query(configuration, mappedStatement, param);
  12.         return query;
  13.     }
  14.     @Override
  15.     public <T> T selectOne(String statementId, Object... params) throws Exception {
  16.         List<Object> objects = selectList(statementId, params);
  17.         if (objects.size() == 1) {
  18.             return (T) objects.get(0);
  19.         } else {
  20.             throw new RuntimeException("返回结果过多");
  21.         }
  22.     }
  23.     @Override
  24.     public <T> T getMapper(Class<?> mapperClass) {
  25.         Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
  26.             @Override
  27.             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  28.                     // selectOne
  29.                 String methodName = method.getName();
  30.                 // className:namespace
  31.                 String className = method.getDeclaringClass().getName();
  32.                 //statementId
  33.                 String statementId = className+'.'+methodName;
  34.                 Type genericReturnType = method.getGenericReturnType();
  35.                 //判断是否实现泛型类型参数化
  36.                 if (genericReturnType instanceof ParameterizedType){
  37.                     List<Object> objects = selectList(statementId,args);
  38.                     return objects;
  39.                 }
  40.                 return selectOne(statementId,args);
  41.             }
  42.         });
  43.         return (T) proxyInstance;
  44.     }
  45. }
复制代码
定义业务数据dao接口
  1. public interface IUserDao {
  2.     //查询所有用户
  3.     public List<User> findAll() throws Exception;
  4.     //根据条件进行用户查询
  5.     public User findByCondition(User user) throws Exception;
  6. }
复制代码
接下来我们只需获取到代理对象,调用方法即可。
  1. public class Main2 {
  2.     public static void main(String[] args) throws Exception {
  3.         InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
  4.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
  5.         SqlSession sqlSession = sqlSessionFactory.openSession();
  6.                 //获取到代理对象
  7.         IUserDao userDao = sqlSession.getMapper(IUserDao.class);
  8.         List<User> all = userDao.findAll();
  9.         for (User user1 : all) {
  10.             System.out.println(user1);
  11.         }
  12.     }
  13. }
复制代码


总结

为了解决JDBC操作数据库存在的问题,我们主要干了这些事

  • 定义sql配置文件来存放数据源、sql语句等信息。
  • 解析xml文件,存放到类对象Configuration、MappedStatement中。
  • 通过反射、自省等技术完成了参数的动态设置、返回结果集的封装
  • 为了解决statementId硬编码问题,我们使用了代理模式创建代理类来获取statementId信息。
  • 在过程中使用到了构建者模式、工厂模式。
以下为本文的大体流程图:

源码以及数据库建表语句链接 :java自定义简易持久层框架
<blockquote>
如果本文对你有帮助,请右下角点下
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

锦通

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表