最近在读刘增辉老师所著的《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语句关联。
说明:以上内容了解下即可,因为按我的风格,特别不喜欢纯理论纯文字的东西,看过我以往博客的读者可能有这个意识,我更喜欢具体代码实战,比如如何使用一个新技术,某一段代码是为了解决什么问题……
关于Maven的相关内容,大家可以参考我之前的博客 Spring入门(四):使用Maven管理Spring项目 。
我一直认为,理解一门技术最好的方式,是通过一个具体的例子,比如Hello World,哈哈。
所以,首先我们要新建个Maven项目,使用IDEA新建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.zwwhnly</groupId>
    <artifactId>mybatis-action</artifactId>
    <version>1.0-SNAPSHOT</version>
    
</project> 
  
 
首先,我们设置源代码的编码方式为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文件,需要手动导入下,否则是下图这样的情况:
 
 
怎么手动导入呢?点击下IDEA右下角提示的Import Changes即可。
 
 
 
 
至此,Maven项目创建完毕。
首先执行如下语句创建数据库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'); 
 首先在src/main/resources目录下创建mybatis-config.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="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> 
 配置简单讲解:
在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> 
 配置简单讲解:
在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
在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
源码地址: https://github.com/zwwhnly/mybatis-action.git ,欢迎下载。
刘增辉《MyBatis从入门到精通》
IntelliJ IDEA中创建xml文件
欢迎扫描下方二维码关注微信公众号:「申城异乡人」,博客内容会同步更新。