Mybatis源码分析之(一)搭建一个mybatis框架(写一个mybatis的Demo)

x33g5p2x  于2022-01-11 转载在 其他  
字(4.9k)|赞(0)|评价(0)|浏览(393)

数据库工作:

首先准备工作,安装mysql,并且新建一张t_demo表

CREATE TABLE `t_demo` (
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `t_demo` VALUES ('name1', 1);
INSERT INTO `t_demo` VALUES ('name2', 2);
INSERT INTO `t_demo` VALUES ('name3', 3);

JAVA工作:

下面就是java中的事情了。LZ用的maven来构建项目的

下面是pom.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.ahpu.wcj</groupId>
    <artifactId>mybatisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- mybatis版本号 -->
        <mybatis.version>3.4.2</mybatis.version>
    </properties>
    <dependencies>

        <!--mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>

    </dependencies>



</project>
new SqlSessionFactoryBuilder().build();//这个使用mybatis的入口,其中要的参数是xml配置的输入流1

所以我们来配置一下mybatis的配置文件

mybatis.cfg.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>

    <!-- 引入外部配置文件 -->
    <properties resource="mysql.properties"></properties>
    <environments default="default">
        <environment id="default">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>

            </dataSource>
        </environment>
    </environments>

    <mappers>

        <mapper class="mapper.TDemoMapper"></mapper>
    </mappers>
</configuration>

其中LZ引用了mysql.properties的资源,所以新建mysql.properties文件,是mysql的连接信息
mysql.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root1234

接下来我们要新建entity和mapper
TDemo

package entity;

public class TDemo {
    int id;
    String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "TDemo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

TDemoMapper

package mapper;

import entity.TDemo;

import java.util.List;

public interface TDemoMapper {
    List<TDemo> getAll();
}

最后新建mapper的映射文件

TDemoMapper.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="mapper.TDemoMapper">

    <resultMap id="baseMap" type="entity.TDemo">
        <result property="id" column="id" jdbcType="INTEGER"></result>
        <result property="name" column="name" jdbcType="VARCHAR"></result>

    </resultMap>
    <select id="getAll" resultMap="baseMap">
        select * from t_demo
    </select>
</mapper>

到这个,mybatis配置文件就建好了。接下来我们就要来使用mybatis了
新建MybatisUtil,这个是用来解析xml,拿到sqlsession的类
MybatisUtil

package util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {

    public static SqlSession getSqlsession(){
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(MybatisUtil.class.getClassLoader().getResourceAsStream("mybatis.cfg.xml"));
        return build.openSession();
    }

}

最后测试一下是否搭建成功
Test

package test;

import entity.TDemo;
import mapper.TDemoMapper;
import org.apache.ibatis.session.SqlSession;
import util.MybatisUtil;

import java.util.List;

public class Test {

    public static void main(String[] args) {
        SqlSession sqlsession = MybatisUtil.getSqlsession();
        TDemoMapper mapper = sqlsession.getMapper(TDemoMapper.class);
        List<TDemo> all = mapper.getAll();
        for (TDemo item : all)
            System.out.println(item);
    }
}
运行结果如下
----------------------------------
TDemo{id=1, name='name1'}
TDemo{id=2, name='name2'}
TDemo{id=3, name='name3'}

可以看到,确实从数据库里取出了数据。

这个整个项目的结构图

相关文章