首页 > 其他 > 详细

13.光脚造飞机自定义MyBatis

时间:2020-07-17 00:15:58      阅读:60      评论:0      收藏:0      [点我收藏+]

13.光脚造飞机自定义MyBatis

首先Mybatis最重要的几个类和接口

  • class Resources(加载配置文件的类)

  • class SqlSessionFactoryBuilder(创建SqlSessionFactory工厂类)

  • interface SqlSessionFactory(创建SqlSession 工厂)

  • interface SqlSession extends Closeable(SqlSession 内部封装了大量的执行sql语句的方法)

 

 

13.1 搭建环境 导入依赖

第一步:搭建环境 导入依赖

目录结构

技术分享图片

 

 <dependencies>
     <!--mysql数据库驱动-->
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>8.0.20</version>
     </dependency>
     <!--junit测试-->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13</version>
     </dependency>
     <dependency>
         <groupId>log4j</groupId>
         <artifactId>log4j</artifactId>
         <version>1.2.17</version>
     </dependency>
      <!--解析xml-->
     <dependency>
         <groupId>dom4j</groupId>
         <artifactId>dom4j</artifactId>
         <version>1.6.1</version>
     </dependency>
     <!--Jaxen是一个Java编写的开源的XPath库-->
     <dependency>
         <groupId>jaxen</groupId>
         <artifactId>jaxen</artifactId>
         <version>1.1.6</version>
     </dependency>
 </dependencies>

 

 

13.2 编写主配置文件mybatis-config.xml

第二步:编写主配置文件mybatis-config.xml

 <?xml version="1.0" encoding="UTF-8" ?>
 ?
 <configuration>
     <!--environment 元素体中包含了事务管理和连接池的配置。开发环境可以是多套的-->
     <typeAliases>
         <package name="com.xuan.pojo"/>
     </typeAliases>
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC"/>
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                 <!--useSSL是协议 后面两个是设置字符集UTF-8 最后是设置时区(mysql8以上都需要)-->
                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                 <property name="username" value="root"/>
                 <property name="password" value="root"/>
             </dataSource>
         </environment>
     </environments>
     <!-- mappers 元素则包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。-->
     <mappers>
         <mapper resource="com/xuan/mapper/UserMapper.xml"/>
     </mappers>
 </configuration>

 

 

13.3 编写实体类和接口

第三步:编写实体类和接口(getter,setter略)

 public class User implements Serializable {
 ?
     private Integer id;
     private String name;
     private String email;
     private String phone;
     private Integer gender;
     private String password;
     private Integer age;
     private Date create_time;
     private Date update_time;
 public interface UserMapper {
 ?
     //查询方法
     List<User> findAll() throws Exception;
 ?
     User findById(Integer id) throws Exception;
 ?
     //模糊查询
     List<User> findUserLike(String value) throws Exception;
 ?
     //增加方法
     void addUser(User user) throws Exception;
 ?
     //增加方法
     void addUser2(Map<String,Object> map) throws Exception;
 ?
     //删除方法
     void deleteUser(Integer id) throws Exception;
 ?
     //修改方法
     Integer updateUser(User user)throws Exception;
 }

 

 

13.4 编写接口对应的配置文件

第四步:编写接口对应的配置文件

 <?xml version="1.0" encoding="UTF-8" ?>
 ?
 <!--namespace命名空间-->
 <mapper namespace="com.xuan.mapper.UserMapper">
     <!--resultType返回类型-->
     <select id="findAll" resultType="User">
        select * from mybatis.user
     </select>
 ?
     <!--通过id查询一个user对象-->
     <select id="findById" parameterType="Integer" resultType="User">
        select * from user where id=#{id}
     </select>
 ?
     <!--模糊查询user集合-->
     <select id="findUserLike"  resultType="User">
        select * from user where name like #{value}
     </select>
 ?
 ?
     <!--添加一个User对象-->
     <insert id="addUser" parameterType="User" >
        insert into user (name,email,phone,gender,password,age,create_time,update_time) values (#{name},#{email},#{phone},#{gender},#{password},#{age},#{create_time},#{update_time});
     </insert>
 ?
     <!--添加一个User对象-->
     <insert id="addUser2" parameterType="map" >
        insert into user (name,age,email) values (#{isName},#{isAge},#{email});
     </insert>
 ?
     <!--删除一个User对象-->
     <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id}
     </delete>
 ?
     <!--修改User字段-->
     <update id="updateUser" parameterType="User"  >
        update user set name=#{name},email=#{email},phone=#{phone},gender=#{gender},password=#{password},age=#{age},create_time=#{create_time},update_time=#{update_time} where id=#{id}
     </update>
 </mapper>

 

 

13.5 编写测试类(把改写的都写暂时忽略爆红因为我们需要自己创建相应的类)

第五步:编写测试类

 package com.xuan.mapper;
 ?
 import com.xuan.mybatis.io.Resources;
 import com.xuan.mybatis.sqlsession.SqlSession;
 import com.xuan.mybatis.sqlsession.SqlSessionFactory;
 import com.xuan.mybatis.sqlsession.SqlSessionFactoryBuilder;
 import com.xuan.pojo.User;
 ?
 import org.junit.Test;
 ?
 import java.io.InputStream;
 import java.util.List;
 ?
 /**
  * xuan
  * 2020/7/12
  * 1870136088@qq.com
  **/
 public class UserMapperTest {
 ?
     @Test
     public  void testFindAll() throws Exception {
 ?
         //1.加载配置文件
         InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
 ?
         //2.获取SqlSessionFactory工厂对象
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 ?
         //3.获取SqlSession对象用来创建执行sql语句的对象
         SqlSession session = sqlSessionFactory.openSession();
 ?
         //4.通过SqlSession创建执行sql语句的对象
         UserMapper mapper = session.getMapper(UserMapper.class);
 ?
         //5.执行mapper接口中方法
         List<User> users = mapper.findAll();
 ?
         //6.遍历users
         for (User user : users) {
             System.out.println(user);
        }
         //7.释放资源
         session.close();
         inputStream.close();
 ?
    }
 ?
 ?
 }

 

下面的都是关键 按照爆红一步步排错

 

13.6 编写Resources类

第六步:编写Resources类

 package com.xuan.mybatis.io;
 ?
 import java.io.InputStream;
 ?
 public class Resources {
 ?
     //根据传入参数获取一个字节输入流
     public static InputStream getResourceAsStream(String filePath){
  //通过该类的字节码文件获取到类加载器再获取到该类的流关联到文件
         return Resources.class.getClassLoader().getResourceAsStream(filePath);
    }
 }

 

 

13.7 编写SqlSessionFactoryBuilder类

编写SqlSessionFactoryBuilder类 并通过其build方法获取到SqlSession对象

 package com.xuan.mybatis.sqlsession;
 ?
 import com.xuan.mybatis.config.Configuration;
 import com.xuan.mybatis.sqlsession.Default.DefaultSqlSessionFactory;
 import com.xuan.utils.XMLConfigBuilder;
 ?
 import java.io.InputStream;
 import java.sql.Connection;
 ?
 public class SqlSessionFactoryBuilder {
 ?
     /**
      * 创建一个build方法 传入字节输入流获取一个SqlSessionFactory工厂对象
      * 根据参数的字节输入流构建一个SqlSessionFactory工厂
      * 涉及到要解析xml
      * @param config
      * @return
      */
     public SqlSessionFactory build(InputStream config){
         Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
         return new DefaultSqlSessionFactory(cfg);
    }
 }

 

 

 

13.8 编写SqlSessionFactory接口以及其实现类

第八步:编写SqlSessionFactory接口以及其实现类

 package com.xuan.mybatis.sqlsession;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 public interface SqlSessionFactory {
 ?
     /**
      * 用于创建SqlSession对象
      * @return
      */
     SqlSession openSession();
 }
 package com.xuan.mybatis.sqlsession.Default;
 ?
 import com.xuan.mybatis.config.Configuration;
 import com.xuan.mybatis.sqlsession.SqlSession;
 import com.xuan.mybatis.sqlsession.SqlSessionFactory;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 public class DefaultSqlSessionFactory implements SqlSessionFactory {
 ?
 ?
     private Configuration cfg;
     public DefaultSqlSessionFactory(Configuration config){
         this.cfg=config;
    }
 ?
     @Override
     public SqlSession openSession() {
         return new DefautSqlSession(cfg);
    }
 }

 

 

13.9 编写SqlSession接口以及其实现类

第九步:编写SqlSession以及实现类(这个类的核心是创建mapper接口的代理对象)

 package com.xuan.mybatis.sqlsession;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 //mybatis的核心类 可以创建mapper接口的代理对象
 public interface SqlSession {
 ?
     /**
      * 根据参数创建一个代理对象
      * @param mapperInterfaceClass
      * @param <T>
      * @return
      */
     <T> T getMapper(Class<T> mapperInterfaceClass);
 ?
     /**
      * 释放资源
      */
     void close();
 }
 package com.xuan.mybatis.sqlsession.Default;
 ?
 import com.xuan.mybatis.config.Configuration;
 import com.xuan.mybatis.config.Mapper;
 import com.xuan.mybatis.sqlsession.SqlSession;
 import com.xuan.utils.DataSourceUtil;
 import com.xuan.utils.Executor;
 ?
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.sql.Connection;
 import java.sql.SQLException;
 import java.util.Map;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 public class DefautSqlSession implements SqlSession {
     private Configuration cfg;
     private Connection connection;
     public DefautSqlSession(Configuration cfg) {
         this.cfg=cfg;
         this.connection= DataSourceUtil.getConnection(cfg);
    }
 ?
     /**
      * 创建代理对象
      * 代理对象第一个参数是类加载器(你代理谁就用谁的类加载器)
      * 第二个参数是接口数组 由于代理的对象本身就是一个数据所以直接写就行
      * 第三个参数就是InvocationHandler 里面写如何代理
      * @param mapperInterfaceClass
      * @param <T>
      * @return
      */
     @Override
     public <T> T getMapper(Class<T> mapperInterfaceClass) {
        return (T) Proxy.newProxyInstance(mapperInterfaceClass.getClassLoader(), new Class[]{mapperInterfaceClass},
                 new InvocationHandler() {
                     /**
                      * 用于对方法进行增强
                      * @param proxy
                      * @param method
                      * @param args
                      * @return
                      * @throws Throwable
                      */
                     @Override
                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                         Map<String, Mapper> mappers = cfg.getMappers();
                         //首先定位一个mapper接口为 全限定类名+方法名
                         String methodName=method.getName();
                         String className=method.getDeclaringClass().getName();
                         //然后组合他们
                         String key =className+"."+methodName;
 ?
                         //获取完key之后获取value 也就是mapper对象也即是sql语句加上实体类的全限定类名
                         Mapper mapper =mappers.get(key);
                         //判断mapper是否为空
                         if (mapper==null){
                             throw new IllegalArgumentException("传的参数有问题");
                        }
                         //没问题的话就调用工具类查询所有
                         return new Executor().selectList(mapper, connection);
                    }
                });
    }
 ?
     @Override
     public void close() {
 ?
         if (connection!=null){
             try {
                 connection.close();
            } catch (SQLException throwables) {
                 throwables.printStackTrace();
            }
        }
 ?
    }
 }

 

 

13.10 导入XMLConfigBuilder类 里面通过dom4j和xpath解析xml

第十步:导入XMLConfigBuilder类 这里需要明确的是SqlSessionFactoryBuilder的build方法是需要关联字节流的也就是说需要解 析xml文件以获得我们需要的信息(也就是主配置文件和mapper映射配置文件信息)

下面先用xml 所以注释掉了注解

 package com.xuan.utils;
 ?
 //import com.xuan.mybatis.annotation.Select;
 ?
 import com.xuan.mybatis.config.Configuration;
 import com.xuan.mybatis.config.Mapper;
 import com.xuan.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.util.HashMap;
 import java.util.List;
 import java.util.Map;
 ?
 public class XMLConfigBuilder {
 ?
 ?
 ?
     /**
      * 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
      * 使用的技术:
      *     dom4j+xpath 需要导入连个坐标
      */
     public static Configuration loadConfiguration(InputStream config){
         try{
             //定义封装连接信息的配置对象(mybatis的配置对象)
             Configuration cfg = new Configuration();
 ?
             //1.获取SAXReader对象
             SAXReader reader = new SAXReader();
             //2.根据字节输入流获取Document对象
             Document document = reader.read(config);
             //3.获取根节点
             Element root = document.getRootElement();
             //4.使用xpath中选择指定节点的方式,获取所有property节点
             List<Element> propertyElements = root.selectNodes("//property");
             //5.遍历节点
             for(Element propertyElement : propertyElements){
                 //判断节点是连接数据库的哪部分信息
                 //取出name属性的值
                 String name = propertyElement.attributeValue("name");
                 if("driver".equals(name)){
                     //表示驱动
                     //获取property标签value属性的值
                     String driver = propertyElement.attributeValue("value");
                     cfg.setDriver(driver);
                }
                 if("url".equals(name)){
                     //表示连接字符串
                     //获取property标签value属性的值
                     String url = propertyElement.attributeValue("value");
                     cfg.setUrl(url);
                }
                 if("username".equals(name)){
                     //表示用户名
                     //获取property标签value属性的值
                     String username = propertyElement.attributeValue("value");
                     cfg.setUsername(username);
                }
                 if("password".equals(name)){
                     //表示密码
                     //获取property标签value属性的值
                     String password = propertyElement.attributeValue("value");
                     cfg.setPassword(password);
                }
            }
             //取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
             List<Element> mapperElements = root.selectNodes("//mappers/mapper");
             //遍历集合
             for(Element mapperElement : mapperElements){
                 //判断mapperElement使用的是哪个属性
                 Attribute attribute = mapperElement.attribute("resource");
                 if(attribute != null){
                     System.out.println("使用的是XML");
                     //表示有resource属性,用的是XML
                     //取出属性的值
                     String mapperPath = attribute.getValue();//获取属性的值"com/xuan/mapper/UserMapper.xml"
                     //把映射配置文件的内容获取出来,封装成一个map
                     Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
                     //给configuration中的mappers赋值
                     cfg.setMappers(mappers);
                }else{
                    /* System.out.println("使用的是注解");
                     //表示没有resource属性,用的是注解
                     //获取class属性的值
                     String daoClassPath = mapperElement.attributeValue("class");
                     //根据daoClassPath获取封装的必要信息
                     Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
                     //给configuration中的mappers赋值
                     cfg.setMappers(mappers);*/
                }
            }
             //返回Configuration
             return cfg;
        }catch(Exception e){
             throw new RuntimeException(e);
        }finally{
             try {
                 config.close();
            }catch(Exception e){
                 e.printStackTrace();
            }
        }
 ?
    }
 ?
     /**
      * 根据传入的参数,解析XML,并且封装到Map中
      * @param mapperPath   映射配置文件的位置
      * @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
      *         以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
      */
     private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
         InputStream in = null;
         try{
             //定义返回值对象
             Map<String,Mapper> mappers = new HashMap<String,Mapper>();
             //1.根据路径获取字节输入流
             in = Resources.getResourceAsStream(mapperPath);
             //2.根据字节输入流获取Document对象
             SAXReader reader = new SAXReader();
             Document document = reader.read(in);
             //3.获取根节点
             Element root = document.getRootElement();
             //4.获取根节点的namespace属性取值
             String namespace = root.attributeValue("namespace");//是组成map中key的部分
             //5.获取所有的select节点
             List<Element> selectElements = root.selectNodes("//select");
             //6.遍历select节点集合
             for(Element selectElement : selectElements){
                 //取出id属性的值     组成map中key的部分
                 String id = selectElement.attributeValue("id");
                 //取出resultType属性的值 组成map中value的部分
                 String resultType = selectElement.attributeValue("resultType");
                 //取出文本内容           组成map中value的部分 
               String queryString = selectElement.getText(); 
               //创建Key 
               String key = namespace+"."+id; 
               //创建Value 
               Mapper mapper = new Mapper(); 
               mapper.setSql(queryString); 
               mapper.setResultType(resultType); 
               //把key和value存入mappers中 
               mappers.put(key,mapper); 
          } 
           return mappers; 
      }catch(Exception e){ 
           throw new RuntimeException(e); 
      }finally{ 
           in.close(); 
      } 
  } 

   /** 
    * 根据传入的参数,得到dao中所有被select注解标注的方法。 
    * 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息 
    * @param daoClassPath 
    * @return 
    */ 
  /* private static Map<String,Mapper> loadMapperAnnotation(String daoClassPath)throws Exception{ 
       //定义返回值对象 
       Map<String,Mapper> mappers = new HashMap<String, Mapper>(); 

       //1.得到dao接口的字节码对象 
       Class daoClass = Class.forName(daoClassPath); 
       //2.得到dao接口中的方法数组 
       Method[] methods = daoClass.getMethods(); 
       //3.遍历Method数组 
       for(Method method : methods){ 
           //取出每一个方法,判断是否有select注解 
           boolean isAnnotated = method.isAnnotationPresent(Select.class); 
           if(isAnnotated){ 
               //创建Mapper对象 
               Mapper mapper = new Mapper(); 
               //取出注解的value属性值 
               Select selectAnno = method.getAnnotation(Select.class); 
               String queryString = selectAnno.value(); 
               mapper.setQueryString(queryString); 
               //获取当前方法的返回值,还要求必须带有泛型信息 
               Type type = method.getGenericReturnType();//List<User> 
               //判断type是不是参数化的类型 
               if(type instanceof ParameterizedType){ 
                   //强转 
                   ParameterizedType ptype = (ParameterizedType)type; 
                   //得到参数化类型中的实际类型参数 
                   Type[] types = ptype.getActualTypeArguments(); 
                   //取出第一个 
                   Class domainClass = (Class)types[0]; 
                   //获取domainClass的类名 
                   String resultType = domainClass.getName(); 
                   //给Mapper赋值 
                   mapper.setResultType(resultType); 
               
               //组装key的信息 
               //获取方法的名称 
               String methodName = method.getName(); 
               String className = method.getDeclaringClass().getName(); 
               String key = className+"."+methodName; 
               //给map赋值 
               mappers.put(key,mapper); 
           
       
       return mappers; 
   
*/ 

}

 

 

 

13.11 编写配置文件解析关联的Mapper类和Configuration类

第十一步:编写配置文件解析关联的Mapper类 这里的Mapper类就涉及解析的sql语句和结果类型的全限定类名

Configuration类就包含主配置文件的数据库连接信息以及mapper映射

 package com.xuan.pojo;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 public class Mapper {
 ?
     /**
      * Mapper用于封装sql语句以及结果类型的全限定类名
      */
     private String sql;
     private String resultType;
 ?
     public String getSql() {
         return sql;
    }
 ?
     public void setSql(String sql) {
         this.sql = sql;
    }
 ?
     @Override
     public String toString() {
         return "Mapper{" +
                 "sql=‘" + sql + ‘\‘‘ +
                 ", resultType=‘" + resultType + ‘\‘‘ +
                 ‘}‘;
    }
 ?
     public String getResultType() {
         return resultType;
    }
 ?
     public void setResultType(String resultType) {
         this.resultType = resultType;
    }
 }
 package com.xuan.mybatis.config;
 ?
 import com.xuan.pojo.Mapper;
 ?
 import java.util.Map;
 ?
 /**
  * xuan
  * 2020/7/14
  * 1870136088@qq.com
  **/
 public class Configuration {   //mybatis自动配置类
 ?
     /**
      * 定义连接的信息 匹配XMLConfigBuilder类中数据库信息
      */
     private String driver;
     private String url;
     private String username;
     private String password;
 ?
     Map<String, Mapper> mappers;
 ?
     /**
      * 为了防止后面的mapper覆盖前面的mapper我们不能直接赋值 应该添加在后面
      * @param mappers
      */
     public void setMappers(Map<String, Mapper> mappers) {
         this.mappers.putAll(mappers);
    }
 ?
     public String getDriver() {
         return driver;
    }
 ?
     public void setDriver(String driver) {
         this.driver = driver;
    }
 ?
     public String getUrl() {
         return url;
    }
 ?
     public void setUrl(String url) {
         this.url = url;
    }
 ?
     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 Map<String, Mapper> getMappers() {
         return mappers;
    }
 }

 

 

13.12 进行级联关联(将几个核心类和接口)

第十二步:进行级联关联 将SqlSessionFactoryBuilder关联DefaultSqlSessionFactory(SqlSessionFactory的实现类)

将SqlSessionFactory关联DefaultSqlSession(SqlSession的实现类)

  • 代码实现已经写在上面了

  • 关键就是返回值进行实现类的传值,再通过构造方法获取到配置的值

  • 另一个关键是动态代理的实现 上面DefaultSqlSession中有写这里再强调一下

 /**
  * 创建代理对象
  * 代理对象第一个参数是类加载器(你代理谁就用谁的类加载器)
  * 第二个参数是接口数组 由于代理的对象本身就是一个数据所以直接写就行
  * 第三个参数就是InvocationHandler 里面写如何代理
  * @param mapperInterfaceClass
  * @param <T>
  * @return
  */
 @Override
 public <T> T getMapper(Class<T> mapperInterfaceClass) {
    return (T) Proxy.newProxyInstance(mapperInterfaceClass.getClassLoader(), new Class[]{mapperInterfaceClass},
                 new InvocationHandler() {
                     /**
                      * 用于对方法进行增强
                      * @param proxy
                      * @param method
                      * @param args
                      * @return
                      * @throws Throwable
                      */
                     @Override
                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                         Map<String, Mapper> mappers = cfg.getMappers();
                         //首先定位一个mapper接口为 全限定类名+方法名
                         String methodName=method.getName();
                         String className=method.getDeclaringClass().getName();
                         //然后组合他们
                         String key =className+"."+methodName;
 ?
                         //获取完key之后获取value 也就是mapper对象也即是sql语句加上实体类的全限定类名
                         Mapper mapper =mappers.get(key);
                         //判断mapper是否为空
                         if (mapper==null){
                             throw new IllegalArgumentException("传的参数有问题");
                        }
                         //没问题的话就调用工具类查询所有
                         return new Executor().selectList(mapper, connection);
                    }
                });
 }

 

 

13.13 由于需要获取数据库连接对象以及释放所以我们需要写一个获取连接的工具类

第十三步:写一个获取数据连接的工具类

 package com.xuan.utils;
 ?
 import com.xuan.mybatis.config.Configuration;
 ?
 import java.sql.Connection;
 import java.sql.DriverManager;
 ?
 public class DataSourceUtil {
 ?
     /**
      * 用于获取一个连接
      * @param cfg
      * @return
      */
     public static Connection getConnection(Configuration cfg){
         try {
             Class.forName(cfg.getDriver());
             return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
        }catch(Exception e){
             throw new RuntimeException(e);
        }
    }
 }

 

 

13.14 在使用动态代理最后我们是调用Executor工具类的selectList方法查询到所有的(参数是mapper和 connection)(了解)

第十四步:使用工具类Executor查询所有信息(对应mapper接口的findAll)这个类是负责执行Sql并且封装结果

 package com.xuan.utils;
 ?
 ?
 import com.xuan.pojo.Mapper;
 ?
 import java.beans.PropertyDescriptor;
 import java.lang.reflect.Method;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.util.ArrayList;
 import java.util.List;
 ?
 /**
  * 负责执行SQL语句,并且封装结果集
  */
 public class Executor {
 ?
     public <E> List<E> selectList(Mapper mapper, Connection conn) {
         PreparedStatement pstm = null;
         ResultSet rs = null;
         try {
             //1.取出mapper中的数据
             String queryString = mapper.getSql();//select * from user
             String resultType = mapper.getResultType();//com.itheima.domain.User
             Class domainClass = Class.forName(resultType);
             //2.获取PreparedStatement对象
             pstm = conn.prepareStatement(queryString);
             //3.执行SQL语句,获取结果集
             rs = pstm.executeQuery();
             //4.封装结果集
             List<E> list = new ArrayList<E>();//定义返回值
             while(rs.next()) {
                 //实例化要封装的实体类对象
                 E obj = (E)domainClass.newInstance();
 ?
                 //取出结果集的元信息:ResultSetMetaData
                 ResultSetMetaData rsmd = rs.getMetaData();
                 //取出总列数
                 int columnCount = rsmd.getColumnCount();
                 //遍历总列数
                 for (int i = 1; i <= columnCount; i++) {
                     //获取每列的名称,列名的序号是从1开始的
                     String columnName = rsmd.getColumnName(i);
                     //根据得到列名,获取每列的值
                     Object columnValue = rs.getObject(columnName);
                     //给obj赋值:使用Java内省机制(借助PropertyDescriptor实现属性的封装)
                     PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);//要求:实体类的属性和数据库表的列名保持一种
                     //获取它的写入方法
                     Method writeMethod = pd.getWriteMethod();
                     //把获取的列的值,给对象赋值
                     writeMethod.invoke(obj,columnValue);
                }
                 //把赋好值的对象加入到集合中
                 list.add(obj);
            }
             return list;
        } catch (Exception e) {
             throw new RuntimeException(e);
        } finally {
             release(pstm,rs);
        }
    }
 ?
 ?
     private void release(PreparedStatement pstm,ResultSet rs){
         if(rs != null){
             try {
                 rs.close();
            }catch(Exception e){
                 e.printStackTrace();
            }
        }
 ?
         if(pstm != null){
             try {
                 pstm.close();
            }catch(Exception e){
                 e.printStackTrace();
            }
        }
    }
 }

 

 

13.15 做总结工作做测试

13.光脚造飞机自定义MyBatis

原文:https://www.cnblogs.com/xuan-study/p/13325284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!