5、手写代码实现MyBatis的查询所有功能

项目准备

1、添加相关依赖

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2、resources根目录下创建全局配置文件 SqlMapConfiguration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--环境配置-->
    <environments default="mysql">
        <!--配置数据库的环境-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据库的四个基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--url中的mybatis就是数据库名称,serverTimezone是时区,没有配置时可能会抛出异常-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="12345"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/dao/UserMapper.xml"/>
    </mappers>
</configuration>

3、创建映射文件 UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace填写的是Mapper接口的全限定名-->
<mapper namespace="com.example.dao.UserMapper">
    <!--
        id必须与接口的方法名一致
        select语句会返回查询结果,所以需要配置一个resultType将查询结果赋值给对象的属性
    -->
    <select id="findAll" resultType="com.example.pojo.User">
        select * FROM user
    </select>
</mapper>

4、创建UserMapper接口(接口文件和映射文件的包结构保证相同)

public interface UserMapper {
    List<User> findAll();
}

5、创建POJO类接收返回的数据 User

package com.example.pojo;

import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String gender;
    private String address;
      //省略了getter、setter和toString方法
 }

6、编写测试类是否可以运行

public class UserMapperTest {
    @Test
    public void testFindAll() throws IOException {
        //    1、读取配置文件(从类路径下开始读取)
        InputStream in = Resources.getResourceAsStream("SqlMapConfiguration.xml");
        //    2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(in);
        //    3、使用工厂生产SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //    4、使用SQLSession创建Dao接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //    5、使用代理对象执行方法
        List<User> users = userMapper.findAll();
        for (User user: users
                ) {
            System.out.println(user);
        }
        //     6、释放资源
        sqlSession.close();
        in.close();

    }
}

编写MyBatis实现的查询方法的代码

1、去除mybatis的jar包

<!--<dependency>-->
    <!--<groupId>org.mybatis</groupId>-->
    <!--<artifactId>mybatis</artifactId>-->
    <!--<version>3.5.3</version>-->
<!--</dependency>-->

去除相关依赖后,测试代码报红,如下:

这说明缺乏MyBatis提供的类对象

还有,因为没有提供MyBatis的jar支持,所以全局配置文件和映射文件上的MyBatis约束不能用了,直接删掉即可

public class Resources
public class SqlSessionFactoryBuilder
public interface SqlSessionFactory
public interface SqlSession

2、创建Resources类

/**
 * 使用类加载器读取配置文件的类
 */
public class Resources {
    /**
     * 根据传入的参数,获取一个字节输入流
     * 通过当前类的字节码获取类加载器,并根据类加载器读取配置文件从而获得一个流
     * @param globalXmlFileName
     * @return
     */
    public static InputStream getResourceAsStream(String globalXmlFileName){
        return Resources.class.getClassLoader().getResourceAsStream(globalXmlFileName);

    }
}

导入自己创建的Resources类,效果如下:

3、创建SqlSessionFactoryBuilder类,
通过该对象的build方法传入全局配置文件的输入流,创建SqlSessionFactory对象

/**
 * 用于常见一个sqlSessionFactory对象
 */
public class SqlSessionFactoryBuilder {
    /**
     * 根据参数的字节输入流来构建一个SQLSessionFactory工厂
     * @param inputStream
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream){
        return null;
    };
}

此时没有SqlSessionFactory类,开发工具提示无法解析

导包

4、创建SqlSessionFactory接口

public interface SqlSessionFactory {
    /**
     * 用于打开一个新的sqlSession对象
     */
    SqlSession openSession();

}

此时没有 SqlSession,开发工具提示无法解析

导包

5、创建 SqlSession接口
SqlSession需要提供getMapper方法来创建代理对象
提供close方法接收与数据库的会话

/**
 * 自定义MyBatis中和数据库交互的核心类
 * 它里面可以创建dao接口的代理对象
 */

public interface SqlSession {
    /**
     * 根据参数创建一个代理对象
     * @param daoInterfaceClass dao的接口字节码
     * @param <T>
     * @return
     */
    <T> T getMapper(Class<T> daoInterfaceClass);

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

导包

全部所需的类都准备完成,还需要实现每个类的功能和职责

3、实现类的功能

1、创建解析xml读取配置信息的类,

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();//获取属性的值
                    //把映射配置文件的内容获取出来,封装成一个map
                    Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
                    //给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.setQueryString(queryString);
                mapper.setResultType(resultType);
                //把key和value存入mappers中
                mappers.put(key,mapper);
            }
            return mappers;
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            in.close();
        }
    }
}

该类需要提供以下依赖

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.1</version>
</dependency>
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>

该类需要提供Configuration类

通过

获取全局配置文件中的properties配置,并设置其数据源

2、创建Configuration类

public class Configuration {

    private String driver;
    private String url;
    private String username;
    private String password;

    private Map<String, Mapper> mappers = new HashMap<>();

    public Map<String, Mapper> getMappers() {
        return 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;
    }
}

此时解析xml的配置类还需要提供mapper类

3、创建Mapper类

这时的Configuration类还缺少setMappers方法

添加方法

 private Map<String, Mapper> mappers;

  public Map<String, Mapper> getMappers() {
      return mappers;
  }

  public void setMappers(Map<String, Mapper> mappers) {
      this.mappers.putAll(mappers);
  }

SqlSessionFactoryBuilder通过该解析类创建SqlSessionFactory对象

/**
 * 用于常见一个sqlSessionFactory对象
 */
public class SqlSessionFactoryBuilder {
    /**
     * 根据参数的字节输入流来构建一个SQLSessionFactory工厂
     * @param inputStream
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream){
        Configuration cfg = XMLConfigBuilder.loadConfiguration(inputStream);
        return new DefaultSqlSessionFactory(cfg);
    };
}

DefaultSqlSessionFactory是SqlSessionFactory的实现类

4、创建SqlSessionFactory实现类DefaultSqlSessionFactory

/**
 * SqlSessionFactory接口的实现类
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory{

    private Configuration configuration;

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

    /**用于获取一个新的操作数据库的对象
     * 该方法需要提供数据库连接
     * @return
     */
    @Override
    public SqlSession openSession() {
        return new DefaultSession(configuration);
    }
}

此时需要创建SqlSession的实现类

创建SqlSession实现类

public class DefaultSession implements SqlSession{

    private Configuration configuration;
    private Connection connection;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
        connection = DataSourceUtils.getConnection(configuration);
    }

    /**
     * 创建代理对象
     * @param daoInterfaceClass dao的接口字节码
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<T> daoInterfaceClass) {
        //创建代理对象

        return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(), new Class[]{daoInterfaceClass}, new MapperProxy(configuration.getMappers(),connection));
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        try {
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

通过DataSourceUtils获取连接

public class DataSourceUtils {

    public static Connection getConnection(Configuration configuration)  {
        try {
            Class.forName(configuration.getDriver());
            return DriverManager.getConnection(configuration.getUrl(),configuration.getUsername(),configuration.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

创建MapperProxy类该类实现的InvocationHandler,GetMapping方法的实现与Spring的AOP实现是原理是相似的

public class MapperProxy implements InvocationHandler{

    private Map<String, Mapper> mappers;
    private Connection connection;

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

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1.获取方法名
        String methodName = method.getName();
        System.out.println(methodName);
        //2.获取方法所在类的名称
        String className = method.getDeclaringClass().getName();
        System.out.println(className);
        //3.组合key
        String key = className+"."+methodName;
        //4.获取mappers中的Mapper对象
        Mapper mapper = mappers.get(key);
        System.out.println(mapper);
        if(mapper==null){
            throw new IllegalArgumentException("传入参数有误");
        }
        //调用工具类查询所有
        return new Executor().selectList(mapper,connection);
    }
}
public class Executor {

    public <E> List<E> selectList(Mapper mapper, Connection conn) {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            //1.取出mapper中的数据
            String queryString = mapper.getQueryString();//select * from user
            String resultType = mapper.getResultType();
            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();
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/Ryuichi/p/13367613.html