1. 程式人生 > >MyBatis原始碼實現之環境準備

MyBatis原始碼實現之環境準備

一、引言

  • 作為一名Java高階開發人員,閱讀原始碼的功底是其重要的基礎技能。除了Spring系列的原始碼之外,就是MyBatis的原始碼閱讀,好了,廢話不多說直接開幹。
  • 宣告:這裡我使用的3.4.6版本。不同版本之間程式碼略有差異

二、搭建

1.建立原始碼閱讀專案(Maven方式)

1.1 以Maven方式建立專案

在這裡我使用的idea建立的(過程略)。效果如下:
在這裡插入圖片描述

2.匯入MyBatis相關原始碼

2.1 下載官方原始碼

2.2 將原始碼匯入專案中

  • 將解壓後的src\main\java裡面的:從org開始,把原始檔拷貝到第一步中建立的專案中(以java為根檔案),拷貝完畢後如下:
    在這裡插入圖片描述
  • 將mybatis-3-mybatis-3.4.6原始碼包中pom.xml中的依賴拷貝到原始碼專案的pom.xml中去,並新增上MySql連線的相關依賴。拷貝後代碼如下:
<?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.gyoomi</groupId>
    <artifactId>Learning-MyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.16</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.22.0-GA</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <optional>true</optional>
        </dependency>
        <!-- Don't upgrade to 2.4+ until mybatis switches to java 7 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
            <optional>true</optional>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <version>4.12.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.3.5</version> <!-- Version 2.4.0 required jdk8 -->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.12.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.12.0</version>
            <scope>test</scope>
        </dependency>
        <!-- Do not go to 2.x until we are on jdk7 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
            <version>1.0.1.Final</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
            <scope>test</scope>
        </dependency>
        <!-- postgresql driver is required to run the refcursor tests -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.1.4.jre6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.1</version> <!-- Stay on 1.7.1 to support Java 6 -->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>eu.codearte.catch-exception</groupId>
            <artifactId>catch-exception</artifactId>
            <version>1.4.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ru.yandex.qatools.embed</groupId>
            <artifactId>postgresql-embedded</artifactId>
            <version>2.5</version>
            <scope>test</scope>
        </dependency>

        <!-- mysql connector jar-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3.建立測試用例

3.1 建立User表

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `deptment` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `status` int(11) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  `remark` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;

3.2 建立UserMapper介面和實現類

  • UserMapper介面
public interface UserMapper {
	
    User save(User user);

}

  • UserMapper介面實現類
public class UserMapperImpl implements UserMapper {

    private static final String NAME_SPACE = "UserMapper.";
    private static SqlSessionFactory ssf;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User save(User user) {
        SqlSession sqlSession = ssf.openSession();
        int rows = sqlSession.insert(NAME_SPACE + "save", user);
        sqlSession.commit();
        if (rows > 0) {
            return user;
        } else {
            return null;
        }
    }
}

3.3 建立MyBatis-config.xml和UserMapper.xml檔案

MyBatis-config.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>

    <settings>
        <setting name="cacheEnabled" value="true" />
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.gyoomi.entity.User" alias="User"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <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="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper.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="UserMapper">

    <insert id="save" parameterType="User">
        <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
            SELECT LAST_INSERT_ID();
        </selectKey>
        INSERT INTO t_user
            (id, user_name, password, deptment, phone, email, status, create_date, remark)
        VALUES
            (null, #{userName}, #{password}, #{deptment}, #{phone}, #{email}, #{status}, #{createDate}, #{remark})
    </insert>
</mapper>

3.4 建立測試的Main方法

建立Main.java(其實這裡是不規範的,一般是要寫JUnit單元測試的。)

public class Main {
    public static void main(String[] args) {
        UserMapper userMapper = new UserMapperImpl();
        User user = new User();
        user.setPassword("123");
        user.setCreateDate(new Date());
        user.setDeptment("研發部門");
        user.setEmail("[email protected]");
        user.setStatus(1);
        user.setUserName("張三");
        user.setPhone("13888888888");
        user.setRemark("系統預設使用者");
        User userToReturn = userMapper.save(user);
        System.out.println(userToReturn);
    }
}

4.測試環境

執行完上述3步後,整體的程式碼結構如下:
在這裡插入圖片描述
執行Main方法後,開啟資料看到t_user表新增了一條記錄。
在這裡插入圖片描述
支援MyBatis的原始碼閱讀的環境搭建並測試完畢。下面就讓我們開始暢快地閱讀原始碼吧!