Day62-了解MyBatis


title: Day62-了解MyBatis
date: 2021-03-30 16:40:41
author: Liu_zimo


原始JDBC操作分析

  • 原始jdbc开发存在的问题:
    1. 数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能
    2. sql语句在代码中硬编码,造成代码不易维护,实际应用sql变化的可能较大,sql变动需要改变java代码
    3. 查询操作时,需要手动将结果集中的数据手动封装到实体中。插入操作时,需要手动将实体的数据设置到sql语句的占位符位置
public void test(){
    //模拟实体对象
    User user = new User();
    user.setId(2);
    user.setUsername("zimo");
    user.setPassword("123456");
    //注册驱动
    Class.forName("com.mysql.jdbc.Driver");
    //获得连接
    Connection connection = DriverWanager.getConnection(url:"jdbc:mysql:///test", "root","123456");
    //获得statement
    PreparedStatement statement = connection.prepareStatement("insert into user(id,username,password) values(?,?,?)");
    //设置占位符参数
    statement.setInt(1, user.getId());
    statement.setString(2, user.getUsername());
    statement.setString(3, user.getPassword());
    //执行更新操作
    statement.executeUpdate();
    //释放资源
    statement.close();
    connection.close();
}
  • 应对上述问题给出的解决方案:
    1. 使用数据库连接池初始化连接资源
    2. 将sql语句抽取到xml配置文件中
    3. 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射

框架

  • 它是我们软件开发中的一套解决方案,不同的框架解决的是不同的问题。
  • 好处:
    • 框架封装了很多的细节,使开发者可以使用极简的方式实现功能。大大提高开发效率。
  • 三层架构:
    • 表现层:是用于展示数据的

    • 业务层:是处理业务需求

    • 持久层:是和数据库交互的

  • 持久层技术解决方案
    • JDBC技术:
      • Cnnection、PreparedStatement、ResultSet
    • Spring的JDBCTemplate:
      • Spring中对JDBC的简单封装
    • Apache的DBUtils:
      • 它和Spring的JDBCTemplate很像,也是对JDBC的简单封装
    • 以上这些都不是框架。JDBC是规范,Spring的JDBCTemplate和Apache的DBUtils都只是工具类

MyBatis框架

  • mybatis是一个持久层框架,用java编写的
    • 它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动,创建连接等繁杂过程它使用了ORM思想实现了结果集的封装。
    • ORM(Object Relational Mappging 对象关系映射):
      • 就是把数据库表和实体类及实体类的属性对应起来,让我们可以操作实体类就实现操作数据库表。

环境搭建bu

CREATE TABLE `user`(
	`id` 		INT(11) 	NOT NULL 	AUTO_INCREMENT,
	`username` 	VARCHAR (32)	NOT NULL 	COMMENT '用户名称',
	`birthday` 	DATETIME 	DEFAULT NULL 	COMMENT '生日',
	`sex` 		CHAR(1) 	DEFAULT NULL 	COMMENT '性别',
	`address` 	VARCHAR(256)	DEFAULT NULL 	COMMENT '地址',
	PRIMARY KEY (id)
)ENGINE = INNODB DEFAULT CHARSuserET=utf8;

INSERT INTO `user`( id ,`username`, `birthday`, `sex`, `address`) VALUES 
('41','老王', '2018-02-27 17:47:08','男','北京'),
('42','小二王', '2018-03-02 15:09:37','女','北京金燕龙'),
('43','老王1', '2018-02-27 17:47:08','男','北京'),
('44','老王2', '2018-02-27 17:47:08','男','北京'),
('45','老王3', '2018-02-27 17:47:08','男','北京');
步骤
  • 第一步:创建Maven工程并导入坐标

  • 第二步:创建实体类和dao的接口

    package com.zimo.domain;
    import java.io.Serializable;
    import java.util.Date;
    /**
     * 用户类
     * @author Liu_zimo
     * @version v0.1 by 2021/3/30 18:05
     */
    public class User implements Serializable {
        private Integer id;
        private String username;
        private Date birthday;
        private String sex;
        private String address;
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public Date getBirthday() { return birthday; }
        public void setBirthday(Date birthday) { this.birthday = birthday; }
        public String getSex() { return sex; }
        public void setSex(String sex) { this.sex = sex; }
        public String getAddress() { return address; }
        public void setAddress(String address) { this.address = address; }
        @Override
        public String toString() {
            return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}';
        }
    }
    --------------------------------------------------------------------------------
    package com.zimo.dao;
    import com.zimo.domain.User;
    import java.util.List;
    /**
     * 用户持久层接口
     * @author Liu_zimo
     * @version v0.1 by 2021/3/30 18:09
     */
    public interface IUserDao {
        List<User> findAll();
    }
    
  • 第三步:创建Mybatis的著配置文件SqlMapConfig.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">
    <!-- mybatis主配置文件 -->
    <configuration>
        <!-- 配置环境 -->
        <environments default="mysql">
            <!-- 配置mysql环境 -->
            <environment id="mysql">
                <!-- 配置事务的类型 -->
                <transactionManager type="JDBC"></transactionManager>
                <!-- 配置数据源(连接池) -->
                <dataSource type="POOLED">
                    <!-- 配置连接数据库的4个基本信息 -->
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    
        <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
        <mappers>
            <mapper resource="com/zimo/dao/IUserDao.xml" />
        </mappers>
    </configuration>
    
  • 第四步:创建映射配置文件IUserDao.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">
    <mapper namespace="com.zimo.dao.IUserDao">
        <!-- 配置查询所有-->
        <select id="findAll" resultType="com.zimo.domain.User">
            select * from user
        </select>
    </mapper>
    
注意事项
  1. 创建IUserDao.xml和IUserDao.java时名称只是命名习惯,在MyBatis中它把持久层的操作接口名称和映射文件也叫做Mapper,所以:IUserDao和IUserMapper是一样的
  2. 在idea中创建目录的时候,它和包是不一样的包在创建时:com.zimo.dao它是三级结构目录在创建时:com.zimo.dao是一级目录
  3. mybatis的映射配置文件位置必须和dao接口的包结构相同
  4. 映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名
  5. 映射配置文件的操作配置,id属性的取值必须是dao接口的方法名
  • 当我们遵从了第三,四,五点之后,我们在开发中就无须再写dao的实现类。

  • 测试案例:XML方式

package com.zimo.test;
import com.zimo.dao.IUserDao;
import com.zimo.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * 入门案例
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 9:43
 */
public class MyBatisTest {
    public static void main(String[] args) throws IOException {
        // 1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        // 3.使用工厂生产SQLSession对象
        SqlSession session = factory.openSession();
        // 4.使用SQLSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        // 5.使用代理对象执行方法
        List<User> list = userDao.findAll();
        for (User user : list) {
            System.out.println(user);
        }
        // 6.释放资源
        session.close();
        in.close();
    }
    // 方式2
    public void function1(){
        // 1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        // 3.使用工厂生产SQLSession对象
        SqlSession session = factory.openSession();
        // 4.执行操作 参数:namespace + id
        List<User> list = session.("com.zimo.dao.IUserDao.findAll");
        for (User user : list) {
            System.out.println(user);
        }
        // 6.释放资源
        session.close();
        in.close();
    }
}
  • 注意事项:
    • 不要忘记在映射配置中告知mybatis要封装到哪个实体类中
      配置的方式:指定实体类的全限定类名
  • 测试案例:dao实现类
package com.zimo.dao.Impl;
import com.zimo.dao.IUserDao;
import com.zimo.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
/**
 * userDaoImpl
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 10:19
 */
public class UserDaoImpl implements IUserDao {
    private SqlSessionFactory factory;

    public UserDaoImpl(SqlSessionFactory factory) {
        this.factory = factory;
    }

    @Override
    public List<User> findAll() {
        // 1.使用工厂创建SqlSession对象
        SqlSession session = factory.openSession();
        List<User> list = session.selectList("com.zimo.dao.IUserDao.findAll");
        session.close();
        return list;
    }
}
package com.zimo.test;
import com.zimo.dao.IUserDao;
import com.zimo.dao.Impl.UserDaoImpl;
import com.zimo.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * 入门案例
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 9:43
 */
public class MyBatisTest1 {
    public static void main(String[] args) throws IOException {
        // 1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        // 3.使用工厂生产SQLSession对象
        UserDaoImpl userDao = new UserDaoImpl(factory);
        // 4.使用代理对象执行方法
        List<User> list = userDao.findAll();
        for (User user : list) {
            System.out.println(user);
        }
        // 5.释放资源
        in.close();
    }
}
  • 测试案例:注解方式
    • 把IUserDao.xml移除,在dao接口的方法上使用@Select注解,并且指定SQL语句
    • 同时需要在SqlMapConfig.xml中的mapper配置时,使用class属性指定dao接口的全限定类名。
package com.zimo.dao;

import com.zimo.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 用户持久层接口
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/3/30 18:09
 */
public interface IUserDao {
    @Select("select * from user")
    List<User> findAll();
}
    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <!-- 如果是用注解来配置的话,此处应该使用class属性指定被注解的dao全限定类名 -->
    <mappers>
<!--        <mapper resource="com/zimo/dao/IUserDao.xml" />-->
        <mapper class="com.zimo.dao.IUserDao" />
    </mappers>
  • 案例细节说明
    1. 路径问题:
      • 相对路径:src/java/main/xxx.xml 不推荐
      • 绝对路径:D:/java/main/xxx.xml 不推荐
      • 推荐使用:
        • 使用类加载器,但是它只能读取类路径的配置文件
        • 使用ServletContext对象的getRealPath()
    2. 创建工厂:mybatis使用了构建者模式,把对象的创建细节隐藏,使用者直接调用方法即可拿到对象
    3. 生产SqlSession使用了工厂模式,优势:解耦(降低类之间的依赖关系)
    4. 创建Dao接口实现类使用了代理模式,优势:不修改源码的基础上对已有方法增强

自定义MyBatis的分析

  1. 使用Dom4j解析XML配置文件

  2. 根据配置文件信息创建Connection对象:注册驱动,获取连接…

  3. 获取与处理对象PreparedStatement

    此时需要SQL语句conn.prepareStatement(sql);

  4. 执行查询

    ResultSet resultSet = preparedStatement.executeQuery();

  5. 遍历结果集用于封装

    List<E> list = new ArrayList();
    while(resultSet.next()){
        E element = (E)Class.forName(配置的全限定类名).newInstance()
        //进行封装 把每个rs的内容都添加到element中
        
        //我们的实体类属性和表中的列名是一致的
        //于是我们就可以看把列名看成是实体类的属性名称
        //就可以使用反射的方式来根据名称获取每个属性,并把值赋进去
        
    	//把element加入到list中
        list.add(element);
    }
    
  6. 返回list

    return list;

  • 想执行以上方法,我们需要给方法提供两个信息

    • 连接信息:配置文件

    • 映射信息:

      1. 执行的SQL语句
      2. 封装结果的实体类全限定类名
      • 把这两个信息组合起来定义成一个对象 → Mapper (key:com.zimo.test.IUserDao.findAll, value:Mapper对象 + String sql + String domainClassPath)

        // 根据dao接口的字节码创建dao的代理对象
        public <T> T getMapper(Class<T> daoInterfaceClass){
            // 类加载器:它使用的和被代理对象是相同的类加载器
            // 代理对象要实现的接口:和被代理对象实现相同的接口
            // 如何代理:它就是增强的方法,我们需要自己来提供。此处是一个InvocationHandler的接口,我们需要写一个该接口的实现类在实现类中调用selectList方法
            Proxy.newProxyInstance(类加载器,代理对象要实现的接口字节码数组,如何代理)
        }
        

自定义MyBatis

  • class Resources
  • class SqlSessionFactoryBuilder
  • interface SqlSessionFactory
  • interface SqlSession

xml配置实现源码

package com.zimo.mybatis.cfg;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定义mybatis配置类
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:16
 */
public class Configuration {
    private String driver;
    private String url;
    private String username;
    private String password;
    private Map<String, Mapper> mappers = new HashMap<String, Mapper>();
    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; }
}
package com.zimo.mybatis.cfg;
/**
 * 用于封装执行的SQL语句和结果类型的全限定类名
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:21
 */
public class Mapper {
    private String queryString; // SQL
    private String resultType;  // 实体类全限定类名
    public String getQueryString() { return queryString; }
    public void setQueryString(String queryString) { this.queryString = queryString; }
    public String getResultType() { return resultType; }
    public void setResultType(String resultType) { this.resultType = resultType; }
}
package com.zimo.mybatis.io;
import java.io.InputStream;
/**
 * 使用类加载器读写配置文件类
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 13:49
 */
public class Resources {
    // 根据传入的参数获取一个字节输入流
    public static InputStream getResourceAsStream(String filePath) {
        return Resources.class.getClassLoader().getResourceAsStream(filePath);
    }
}
package com.zimo.mybatis.sqlsession;
/**
 * 它里面可以创建dao接口的代理对象
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 13:58
 */
public interface SqlSession {
    // 根据参数创建一个代理对象
    <T> T getMapper(Class<T> daoInterfaceClass);
    // 释放资源
    void close();
}
package com.zimo.mybatis.sqlsession;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 13:56
 */
public interface SqlSessionFactory {
    SqlSession openSession();   // 打开一个新的SqlSession对象
}
package com.zimo.mybatis.sqlsession;
import com.zimo.mybatis.cfg.Configuration;
import com.zimo.mybatis.sqlsession.defaults.DefaultSqlSessionFactory;
import com.zimo.mybatis.utils.XMLConfigBuilder;
import java.io.InputStream;
/**
 * 用于创建一个SqlSessionFactory对象
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 13:54
 */
public class SqlSessionFactoryBuilder {
    // 根据参数的字节输入流来构建一个SqlSessionFactory工厂
    public SqlSessionFactory build(InputStream conf){
        Configuration configuration = XMLConfigBuilder.loadConfiguration(conf);
        return new DefaultSqlSessionFactory(configuration);
    }
}
package com.zimo.mybatis.sqlsession.defaults;
import com.zimo.mybatis.cfg.Configuration;
import com.zimo.mybatis.sqlsession.SqlSession;
import com.zimo.mybatis.sqlsession.proxy.MapperProxy;
import com.zimo.mybatis.utils.DataSourceUtil;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:36
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private Connection conn;
    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.conn = DataSourceUtil.getConnection(configuration);
    }
    public <T> T getMapper(Class<T> daoInterfaceClass) {
        return (T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(), new Class[]{daoInterfaceClass}, new MapperProxy(configuration.getMappers(),conn));
    }
    public void close() {
        if (conn != null)
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
package com.zimo.mybatis.sqlsession.defaults;
import com.zimo.mybatis.cfg.Configuration;
import com.zimo.mybatis.sqlsession.SqlSession;
import com.zimo.mybatis.sqlsession.SqlSessionFactory;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:33
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private Configuration configuration;
    public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; }
    // 创建一个新的操作数据库对象
    public SqlSession openSession() { return new DefaultSqlSession(configuration); }
}
package com.zimo.mybatis.sqlsession.proxy;
import com.zimo.mybatis.cfg.Mapper;
import com.zimo.mybatis.utils.Executor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:39
 */
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;
    }
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        // 1.获取方法名
        String methodName = method.getName();
        // 2.获取方法所在类的名称
        String className = method.getDeclaringClass().getName();
        // 3.组合key
        String key = className + "." + methodName;
        // 4.获取mappers中的Mapper对象
        Mapper mapper = mappers.get(key);
        // 5.是否有mapper
        if (mapper == null){
            throw new IllegalArgumentException("Error");
        }
        // 6.调用工具类执行查询所有方法
        return new Executor().selectList(mapper, connection);
    }
}
  • 工具类
package com.zimo.mybatis.utils;
import com.zimo.mybatis.cfg.Configuration;
import java.sql.Connection;
import java.sql.DriverManager;
/**
 * 用干创建数据源的工具类
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 14:53
 */
public class DataSourceUtil {
    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);
        }
    }
}
package com.zimo.mybatis.utils;
import com.zimo.mybatis.cfg.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语句,并且封装结果集
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 9:43
 */
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();//com.zimo.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();
            }
        }
    }
}
package com.zimo.mybatis.utils;

import com.zimo.mybatis.annotations.Select;
import com.zimo.mybatis.cfg.Configuration;
import com.zimo.mybatis.cfg.Mapper;
import com.zimo.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.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/3/31 9:43
 */
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/zimo.mybatis/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.setQueryString(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;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳子陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值