59

MyBatis从入门到精通(一):MyBatis入门

 4 years ago
source link: https://www.tuicool.com/articles/3u632my
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

最近在读刘增辉老师所著的《MyBatis从入门到精通》一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸!

1. MyBatis简介

​ 2001年,Clinton Begin发起了一个名为iBATIS的开源项目,最初侧重于密码软件的研发,后来发展成为一款基于Java的持久层框架。

​ 2004年,Clinton将iBATIS的名字和源码捐赠给了Apache软件基金会。

​ 2010年,核心开发团队决定离开Apache软件基金会,并且将iBATIS改名为MyBatis。

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

​ 与其他的ORM(对象关系映射)框架不同,MyBatis并没有将Java对象与数据库表关联起来,而是将Java方法与SQL语句关联。

说明:以上内容了解下即可,因为按我的风格,特别不喜欢纯理论纯文字的东西,看过我以往博客的读者可能有这个意识,我更喜欢具体代码实战,比如如何使用一个新技术,某一段代码是为了解决什么问题……

2. 创建Maven项目

关于Maven的相关内容,大家可以参考我之前的博客 Spring入门(四):使用Maven管理Spring项目

我一直认为,理解一门技术最好的方式,是通过一个具体的例子,比如Hello World,哈哈。

所以,首先我们要新建个Maven项目,使用IDEA新建Maven项目的方法如下所示:

YrIVRvY.png!web

E36v6nN.png!web

2iQrueI.png!web

刚新建完的Maven项目结构如下所示:

VBR7bmu.png!web

默认生成的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.zwwhnly</groupId>
    <artifactId>mybatis-action</artifactId>
    <version>1.0-SNAPSHOT</version>
    
</project>

eqQnaiI.png!web

首先,我们设置源代码的编码方式为UTF-8:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

接着,设置编译源代码的JDK版本,这里暂时用1.6,可根据自己的实际需要修改,比如修改成1.8:

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

然后,添加重要的MyBatis的依赖坐标和mysql驱动的依赖坐标:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    
</dependencies>

最后,添加下用到的Log4j、JUnit的依赖坐标,最终的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.zwwhnly</groupId>
    <artifactId>mybatis-action</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

在IDEA中,如果没有特殊配置过,修改完pom文件,需要手动导入下,否则是下图这样的情况:

iYzABnn.png!web

怎么手动导入呢?点击下IDEA右下角提示的Import Changes即可。

zUBNban.png!web

7fyU3ii.png!web

至此,Maven项目创建完毕。

3. 简单示例

3.1 数据准备

首先执行如下语句创建数据库mybatis_action_db:

CREATE DATABASE mybatis_action_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

然后执行如下语句创建表country,并添加一些数据:

use mybatis_action_db;

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

3.2 配置MyBatis

首先在src/main/resources目录下创建mybatis-config.xml配置文件,为了后续更快速的创建mybatis-config.xml文件,我们可以按照如下步骤添加模版:

NniUNrr.png!web

zMBNreU.png!web7fuy2ab.png!webjQbYjyM.png!web

nA3meu3.png!web

然后输入如下内容:

<?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="logImpl" value="LOG4J"/>
    </settings>

    <typeAliases>
        <package name="com.zwwhnly.mybatisaction.model"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_action_db"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/zwwhnly/mybatisaction/mapper/CountryMapper.xml"/>
    </mappers>
</configuration>

配置简单讲解:

  • 节点中的logImpl属性配置指定使用LOG4J输出日志。
  • 元素下面配置了一个包名,通常确定一个类的时候需要使用类的全限定名称,例如com.zwwhnly.mybatisaction.model.Country。在MyBatis中需要频繁用到类的全限定名称,为了方便使用,我们配置了com.zwwhnly.mybatisaction.model包,这样配置后,在使用类的时候不需要写包名的部分,只使用Country即可。
  • 环境配置中主要配置了数据库连接,如这里我们使用的是本机MySql中的mybatis_action_db数据库,用户名为root,没有密码(大家可根据自己的实际情况修改数据库及用户名和密码)。
  • 中配置了一个包含完整类路径的CountryMapper.xml,这是一个MyBatis的Sql语句和映射配置文件。

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

在src/main/java下新建包:com.zwwhnly.mybatisaction,然后在这个包下再创建包:model。

在model包下创建数据库表country表对应的实体类Country:

package com.zwwhnly.mybatisaction.model;

public class Country {
    private Integer id;

    private String countryname;

    private String countrycode;

    // 按Alt+Insert快捷键生成get和set方法
}

在src/main/resources下创建目录com/zwwhnly/simple/mapper目录,然后在该目录下创建CountryMapper.xml文件,为了后续更快速的创建Mapper.xml文件,我们可以参考上面的添加mybatis-config.xml模版的方法,这里不再赘述。

最终的CountryMapper.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="com.zwwhnly.mybatisaction.mapper.CountryMapper">
    <select id="selectAll" resultType="Country">
        SELECT id,countryname,countrycode from country
    </select>
</mapper>

配置简单讲解:

  • mapper:XML的根元素,属性namespace定义了当前XML的命名空间。
  • select:我们所定义的一个Select查询。
  • id属性:定义了当前Select查询的唯一id。
  • resultType:定义了当前查询的返回值类型,此处就是指实体类Country,前面配置中提到的包名主要用于这里,如果没有设置包名,此处就需要写成resultType=”com.zwwhnly.mybatisaction.model.Country”。
  • SELECT id,countryname,countrycode from country:查询Sql语句。

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

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

log4j.rootLogger=ERROR, stdout
log4j.logger.com.zwwhnly.mybatisaction.mapper=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 

3.5 编写测试代码

在src/test/java下创建包:com.zwwhnly.mybatisaction.mapper,然后创建测试类CountryMapperTest类,代码如下:

package com.zwwhnly.mybatisaction.mapper;

import com.zwwhnly.mybatisaction.mapper.model.Country;
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 java.io.IOException;
import java.io.Reader;
import java.util.List;

public class CountryMapperTest extends BaseMapperTest {
    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 e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSelectAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            List<Country> countryList = sqlSession.selectList("selectAll");
            printCountryList(countryList);
        } finally {
            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());
        }
    }
}

运行测试代码,输出日志如下:

DEBUG [main] - ==> Preparing: SELECT id,countryname,countrycode from country
DEBUG [main] - ==> Parameters:
TRACE [main] - <== Columns: id, countryname, countrycode
TRACE [main] - <== Row: 1, 中国, CN
TRACE [main] - <== Row: 2, 美国, US
TRACE [main] - <== Row: 3, 俄罗斯, RU
TRACE [main] - <== Row: 4, 英国, GB
TRACE [main] - <== Row: 5, 法国, FR
DEBUG [main] - <== Total: 5
1 中国 CN
2 美国 US
3 俄罗斯 RU
4 英国 GB
5 法国 FR

4. 源码

源码地址: https://github.com/zwwhnly/mybatis-action.git ,欢迎下载。

5. 参考

刘增辉《MyBatis从入门到精通》

IntelliJ IDEA中创建xml文件

6. 最后

欢迎扫描下方二维码关注微信公众号:「申城异乡人」,博客内容会同步更新。

3iuMVfB.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK