MaBatis框架整体梳理

一、项目结构图总览

在这里插入图片描述

二、前期开发准备

2.1创建Maven工程

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
点击finish即可
在这里插入图片描述

2.2pom.xml文件导入相关坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.thinkcoder</groupId>
    <artifactId>selfmybatis</artifactId>
    <version>1.0.0</version>

    <!--打包方式jar包-->
    <packaging>jar</packaging>

    <!--mysql驱动-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!-- 操作日志-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>2.12.1</version>
        </dependency>

        <!--解析xml文件-->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
    </dependencies>
</project>
2.3建立数据库操作的配置文件

建表的sql脚本

CREATE TABLE `user` (
  `name` char(4) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  `id` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User类:属性与数据库表字段名称保持一致

  • 利用了ORM思想:Object Relational Mapping对象关系映射,把实体类的属性和数据库表对应起来,操作实体类就实现操作数据库表
public class User {
    private Integer id;
    private String name;
    private String pwd;

	//getter和setter方法
    public Integer getId() {return id;}
    public void setId(Integer id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getPwd() {return pwd;}
    public void setPwd(String pwd) {this.pwd = pwd;}
	
	//重写toString方法
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

IUserDao接口:操作数据库的接口

public interface IUserDao {
    //查询所有操作
    List<User> findAll();
}

SqlMapConfig.xml文件:配置连接数据库信息及指定映射配置文件位置

<?xml version="1.0" encoding="UTF-8"?>
<!--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/selfproj"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <mapper resource="com/thinkcoder/dao/IUserDao.xml"/>
    </mappers>
</configuration>

IUserDao.xml文件:配置方法映射的sql语句及返回结果类型

<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.thinkcoder.dao.IUserDao">
    <!--配置查询所有记录--><!--id为方法的名称-->
    <select id="findAll" resultType="com.thinkcoder.domain.User">
        select * from user
    </select>
</mapper>

三、自定义MaBatis框架主要类总览

为了搞清主要类之间的调用关系,画了一个时序图,UML可是架构师的利器,要善于使用
在这里插入图片描述
上面的图是重点:下面按照上图调用关系用代码实现

四、自定义MyBatis框架实现

测试类(client)
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接口没有实现类
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user:users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}
Resources类
  • 读取配置文件
public class Resources {

    /**
     * @Description:根据传入的参数,获取一个字节输入流
     * @Author: Think-Coder
     * @Param :filePath
     *
     * 在实际开发中读取配置文件
     *          1.使用类加载器,但是有要求:a文件不能过大,b文件必须在类路径下(classpath)
     *          2.使用ServletContext的getRealPath()
     **/
    public static InputStream getResourceAsStream(String filePath){
        return Resources.class.getClassLoader().getResourceAsStream(filePath);
    }
}
SqlSessionFactoryBuilder
  • 构建者模式创建SqlSessionFactroy工厂
public class SqlSessionFactoryBuilder {
    
    /**
     * @Description:根据参数的字节输入流来构建一个SqlSessionFactory工厂
     * @Author: Think-Coder
     * @Param :config
     **/
    public SqlSessionFactory build(InputStream config) {
        //解析流需要解析xml工具类
        Configuration conf = XMLConfigBuilder.loadConfiguration(config);
        return new DefaultSqlSessionFactory(conf);
    }
}
XMLConfigBuilder类
  • dom4j+xpath技术解析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();//获取属性的值"com/thinkcoder/dao/IUserDao.xml"
                    //把映射配置文件的内容获取出来,封装成一个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();
        }
    }
}
Configuration类
  • 由XMLConfigBuilder解析xml文件返回Configuration对象
/**
 * 自定义MyBatis的配置类
 * @ClassName Configuration
 * @Author thinkcoder
 * @Data 2020/5/20 11:20
 * @Version 1.0
 */
public class Configuration {

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

	//String保存的是全限定类名加方法名,com.thinkcoder.IUserDao.findAll
	//Mapper存的是返回的实体类的全限定类名,com.thinkcoder.domain.User
	//及sql语句
	//通过String可以确定Mapper
    private Map<String, Mapper> mappers;
	
	//getter和setter方法
    public Map<String, Mapper> getMappers() {return mappers;}
    public void setMappers(Map<String, Mapper> mappers) {this.mappers = 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;}
}
Mapper类
/**
 * 用于封装执行的SQL语句和结果类型的全限定类名
 * @ClassName Mapper
 * @Author think-coder
 * @Data 2020/5/20 11:23
 * @Version 1.0
 */
public class Mapper {

    private  String queryString;//SQL
    private  String resultType;//实体类的全限定类名

    public String getResultType() {
        return resultType;
    }

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

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }
}
SqlSessionFactory接口:
public interface SqlSessionFactory {
    /**
     * @Description:用于打开一个新的SqlSession对象
     **/
    SqlSession openSession();
}
DefaultSqlSessionFactory类
  • 实现SqlSessionFactory接口,生成sqlsession对象
/**
 * @ClassName DefaultSqlSessionFactory
 * @Author Think-Coder
 * SqlSessionFactory接口的实现类
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration conf;

    public DefaultSqlSessionFactory(Configuration conf){
        this.conf = conf;
    }
    /**
     * @Description:用于创建一个新的操作数据库对象
     * @Return :SqlSession
     **/
    public SqlSession openSession() {
        return new DefaultSqlSession((conf));
    }
}
SqlSession接口
  • 和数据库交互的核心类
/**
 * 自定义Mybatis中和数据库交互的核心类
 * 里面可以创建dao接口的代理对象
 * @Author Think-Coder
 */
public interface SqlSession {

    /**
     * @Description:根据参数创建一个代理对象
     * @Param :daoInterfaceClass  dao的接口字节码
     **/
    <T> T getMapper(Class<T> daoInterfaceClass);

    /**
     * 释放资源
     */
    void close();
}
DefaultSqlSession类
  • 实现SqlSession接口
/**
 * @ClassName DefaultSqlSession
 * @Author Think-Coder
 * SqlSession接口的实现类
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration conf;
    private Connection connection;

    public DefaultSqlSession(Configuration conf){
        this.conf = conf;
        connection = DataSourceUtil.getConnection(conf);
    }
    /**
     * @Description:用于创建代理对象
     * @Param :daoInterfaceClass  dao的接口字节码
     **/
    public <T> T getMapper(Class<T> daoInterfaceClass) {
        return (T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
                new Class[]{daoInterfaceClass},new MapperProxy(conf.getMappers(),connection));

    }

    /**
     * @Description:释放资源
     **/
    public void close() {
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
DataSourceUtil工具类
  • 用于创建数据源
//用于创建数据源的工具类
public class DataSourceUtil {
    
    //用于获取一个连接
    public static Connection getConnection(Configuration conf){
        try{
            Class.forName(conf.getDriver());
            return  DriverManager.getConnection(conf.getUrl(),conf.getUsername(),conf.getPassword());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
MapperProxy类
  • 用于增强原对象IUserDao接口,增强方法为selectList方法
public class MapperProxy implements InvocationHandler {

    //map的key是全限定类名+方法名
    private Map<String, Mapper> mappers;
    private Connection conn;

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

    //用于对方法的增强,我们的增强其实就是调用selectList方法
    public Object invoke(Object proxy, Method method, Object[] args) 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("传入参数有误");
        }
        //6.调用工具类执行查询所有
        return new Executor().selectList(mapper,conn);
    }
}
Executor 工具类
//负责执行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.getQueryString();//select * from user
            String resultType = mapper.getResultType();//com.thinkecoder.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();
            }
        }
    }
}

五、运行结果及总结

上述实现了查询数据库功能

User{id=1, name='张三', pwd='123'}
User{id=2, name='李四', pwd='128'}

Process finished with exit code 0

上述代码按照去除了Mybatis的依赖,从测试类开始一步一步搭建起来的,读者也可以自己练习一下

  • 160
    点赞
  • 293
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 118
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿成长轨迹

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

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

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

打赏作者

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

抵扣说明:

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

余额充值