第一章 MyBatis 入门

最终项目目录结构如下:

Maven项目目录结构

1.1 MyBatis 简介

MyBatis 是一款优秀的支持自定义 SQL 查询、存储过程和高级映射的持久层框架,消除了几乎所有的 JDBC 代码和参数的手动设置以及结果集的检索。MyBatis 可以使用 XML 或注解进行配置和映射,MyBatis 通过将参数映射到配置的 SQL 形式最终执行的 SQL 语句,最后将执行 SQL 的结果映射成 Java 对象返回。

1.2 创建 Maven 项目

使用 IntelliJ IDEA 作为项目 IDE,首先创建一个 Maven 项目。

打开 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.nwgdk</groupId>
    <artifactId>mybatis-study-01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <-- 添加其他配置 -->
</project>

以上是 Maven 的基础配置,以下我们还需要添加一些常用配置。首先,设置源代码编码方式为 UTF-8,配置如下:

<!-- 设置编码方式为 UTF-8 -->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

设置编译源代码的 JDK 版本为 1.8,配置如下:

<build>
    <plugins>
        <!-- 设置编译源代码的 JDK 版本为:1.8 -->
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

在 pom.xml 文件中添加 MyBatis 依赖:

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

接着添加会用到的 Log4j、Junit 和 MySQL 驱动的依赖。最终的 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>tk.mybatis</groupId>
    <artifactId>simple</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 设置编码方式为 UTF-8 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- 添加 Junit依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 添加 MyBatis 依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- 添加 MySQL 驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 添加 Log4j 依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- 添加 slf4j 依赖 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 设置编译源代码的 JDK 版本为:1.8 -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.3 简单配置让 MyBatis 跑起来

1.3.1 准备数据库

首先创建一个数据库,编码方式设置为 UF-8,可以使用 MySQL 客户端工具 Navicat 来实现。通过执行下面的 SQL 语句创建一个名为 mybatis 的数据库:

CREATE DATABASE mybatis DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

然后在创建一个名为 country 的表并插入一些数据,代码如下:

 CREATE TABLE `country`(
    `id` int NOT NULL AUTO_INCREMENT,
    `countryname` varchar(255) NULL,
    `countrycode` varchar(255) NULL,
    PRIMARY KEY(`id`)
    );

INSERT country(`countryname`,`countrycode`) values ('中国','CN'),('美国','US'),('俄罗斯','RU'),('英国','GB'),('法国','FR');

1.3.2 配置 MyBatis

下面是用最基础的 XML 形式进行 mybatis 配置。

首先在 src/mian/resources 下面创建 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>
        <!-- 指定使用 LOG4J 输出日志 -->
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <typeAliases>
        <!-- 配置包别名 -->
        <package name="tk.mybatis.simple.model"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <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="admin123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/>
    </mappers>

</configuration>

1.3.3 创建实体类和 Mapper.xml 文件

model 包下创建实体类 Country,代码如下:

package tk.mybatis.simple.model;

public class Country {
    private Long id;
    private String countryname;
    private String countrycode;

    public Long getId() {
        return id;
    }

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

    public String getCountryname() {
        return countryname;
    }

    public void setCountryname(String countryname) {
        this.countryname = countryname;
    }

    public String getCountrycode() {
        return countrycode;
    }

    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }
}

1.3.4 配置 Log4j 以便查看 MyBatis 操作数据库的过程

src/resources 文件下创建 log4j.properties 配置文件,输入如下内容:

# 全局配置
log4j.rootLogger = ERROR, stdout
# MyBatis 日志配置
log4j.logger.tk.mybatis.simple.mapper = TRACE
# 控制台输出配置
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.aooender.stdout.layout.ConversionPattern = %5p [%t] - %m%n

1.3.5 编写测试代码让 MyBatis 跑起来

在 src/test/java 下创建 tk.mybatis.simple.mapper 包,然后创建 CountryMapperTest 测试类,代码如下:

package tk.mybatis.simple.mapper;

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 org.junit.BeforeClass;
import org.junit.Test;
import tk.mybatis.simple.model.Country;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class CountryMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException ignore) {
            ignore.printStackTrace();
        }
    }

    @Test
    public void testSelectAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            List<Country> countryList = sqlSession.selectList("selectAll");
            printCountryList(countryList);
        } finally {
            // 不要忘记关闭 sqlSession
            sqlSession.close();
        }
    }

    private void printCountryList(List<Country> countryList) {
        for (Country country : countryList) {
            System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode());
        }
    }
}

上面代码测试成功后,会输出如下日志:

==>  Preparing: SELECT id,countryname,countrycode FROM country; 
==> Parameters: 
<==    Columns: id, countryname, countrycode
<==        Row: 1, 中国, CN
<==        Row: 2, 美国, US
<==        Row: 3, 俄罗斯, RU
<==        Row: 4, 英国, GB
<==        Row: 5, 法国, FR
<==      Total: 5
1     中国  CN
2     美国  US
3    俄罗斯  RU
4     英国  GB
5     法国  FR

猜你喜欢

转载自www.cnblogs.com/nwgdk/p/9695725.html