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

    • 数据库工作:
    • JAVA工作:
    • demo项目地址:

首先,LZ为了照顾一些基础薄弱的同学,所以先带萌新搭一个mybatis的demo,这个在看源码的时候能起到了很大的作用,因为在看源码的时候,会恍然大悟,为什么要这么配置,为什么要这么写。(老鸟可以跳过这篇)

数据库工作:

首先准备工作,安装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


<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.0modelVersion>

    <groupId>com.ahpu.wcjgroupId>
    <artifactId>mybatisDemoartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        
        <mybatis.version>3.4.2mybatis.version>
    properties>
    <dependencies>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.44version>
        dependency>


    dependencies>




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

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

mybatis.cfg.xml



<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=root

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

package entity;

/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 14:58 2018/5/4
 *@Modified By:
 *
 */
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;

/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 14:58 2018/5/4
 *@Modified By:
 *
 */
public interface TDemoMapper {
    List getAll();
}

最后新建mapper的映射文件

TDemoMapper.xml



<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;

/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 14:52 2018/5/4
 *@Modified By:
 *
 */
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;

/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 15:31 2018/5/4
 *@Modified By:
 *
 */
public class Test {

    public static void main(String[] args) {
        SqlSession sqlsession = MybatisUtil.getSqlsession();
        TDemoMapper mapper = sqlsession.getMapper(TDemoMapper.class);
        List 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'}

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

这个整个项目的结构图
Mybatis源码分析之(一)搭建一个mybatis框架(写一个mybatis的Demo)_第1张图片

demo项目地址:

https://github.com/stackisok/mybatisDemo

你可能感兴趣的:(mybatis)