手撸MyBatis从配置文件到读出数据库的模拟实现

Posted leyvan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手撸MyBatis从配置文件到读出数据库的模拟实现相关的知识,希望对你有一定的参考价值。

手动模拟MyBatis入门案例的底层实现:
需要了解的关键技术:
java反射、动态代理(comming soon)

一、Mybatis入门案例

点击此处跳过入门案例


首先看一下MyBatis最基础的入门案例
目标:读取数据库名为mybatis中的user表内容
技术图片
maven依赖

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

Mybatis入门案例的两个配置文件:1.SqlMapConfig.xml 2.IUserDao.xml
1.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">
<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="club/leyvan/dao/IUserDao.xml"/>
    </mappers>
</configuration>

2.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="club.leyvan.dao.IUserDao">
    <select id="findAll" resultType="club.leyvan.domain.User">
        select * from user
    </select>
</mapper>

实体类

package club.leyvan.domain;

import java.util.Date;

/**
 * @Auther: http://www.leyvan.club
 * @Date: 2019/12/13
 * @Description: club.leyvan.domain
 * @version: 1.0
 */
public class User {
    /**
     * `id` int(11) NOT NULL AUTO_INCREMENT,
     *   `username` varchar(32) NOT NULL COMMENT '用户名称',
     *   `birthday` date DEFAULT NULL COMMENT '生日',
     *   `sex` char(1) DEFAULT NULL COMMENT '性别',
     *   `address` varchar(256) DEFAULT NULL COMMENT '地址',
     */
    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 + ''' +
                '}';
    }
}

Dao层接口

package club.leyvan.dao;

import club.leyvan.domain.User;

import java.util.List;

/**
 * @Auther: http://www.leyvan.club
 * @Date: 2019/12/13
 * @Description: club.leyvan.dao
 * @version: 1.0
 */
public interface IUserDao {

    public List<User> findAll();

}

测试类

package club.leyvan.test;

import club.leyvan.dao.IUserDao;
import club.leyvan.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.InputStream;
import java.util.List;

/**
 * @Auther: http://www.leyvan.club
 * @Date: 2019/12/13
 * @Description: club.leyvan.test
 * @version: 1.0
 */
public class Demo {

    public static void main(String[] args) {
        try{
            //加载配置文件
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            //构造者模式创建工厂建造者
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(in);
            //工厂模式创建session
            SqlSession session = factory.openSession();
            //通过动态代理创建代理对象
            IUserDao userDao = session.getMapper(IUserDao.class);
            List<User> list = userDao.findAll();
            for (User user: list) {
                System.out.println(user);
            }
            session.close();
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}

输出结果

User{id=1, username='王五', birthday=null, sex='2', address='null'}
User{id=10, username='张三', birthday=Thu Jul 10 00:00:00 CST 2014, sex='1', address='北京市'}
User{id=16, username='张小明', birthday=null, sex='1', address='河南郑州'}
User{id=22, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=24, username='张三丰', birthday=null, sex='1', address='河南郑州'}
User{id=25, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=26, username='王五', birthday=null, sex='null', address='null'}

二、模拟Mybatis实现上面的入门案例

将maven的依赖删除以后,手动模拟实现上面的入门案例:
[分析]
技术图片
代码实现在GITHUB
结果:

使用的是XML
User{id=1, username='王五', birthday=null, sex='2', address='null'}
User{id=10, username='张三', birthday=2014-07-10, sex='1', address='北京市'}
User{id=16, username='张小明', birthday=null, sex='1', address='河南郑州'}
User{id=22, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=24, username='张三丰', birthday=null, sex='1', address='河南郑州'}
User{id=25, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=26, username='王五', birthday=null, sex='null', address='null'}
使用的是注解
User{id=1, username='王五', birthday=null, sex='2', address='null'}
User{id=10, username='张三', birthday=2014-07-10, sex='1', address='北京市'}
User{id=16, username='张小明', birthday=null, sex='1', address='河南郑州'}
User{id=22, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=24, username='张三丰', birthday=null, sex='1', address='河南郑州'}
User{id=25, username='陈小明', birthday=null, sex='1', address='河南郑州'}
User{id=26, username='王五', birthday=null, sex='null', address='null'}

以上是关于手撸MyBatis从配置文件到读出数据库的模拟实现的主要内容,如果未能解决你的问题,请参考以下文章

嘿~全流程带你基于Pytorch手撸图片分类“框架“--HuClassify

SSM框架MyBatis核心配置文件详解

Java编程(基于图形界面)从文件中读出数据,显示在文本框中

基于Mybatis手撸一个分表插件

基于Mybatis手撸一个分表插件

❤️‍Spring从入门到大神--Spring整合MyBatis