在上一章中我们学习了《MyBatis学习总结(一)——ORM概要与MyBatis快速起步》,这一章主要是介绍MyBatis核心配置文件、使用接口+XML实现完整数据访问、输入参数映射与输出结果映射等内容。

一、MyBatis配置文件概要

MyBatis核心配置文件在初始化时会被引用,在配置文件中定义了一些参数,当然可以完全不需要配置文件,全部通过编码实现,该配置文件主要是是起到解偶的作用。如第一讲中我们用到conf.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>
    <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://127.0.0.1:3306/nfmall?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper resource="mapper/studentMapper.xml"/>-->
        <mapper class="com.zhangguo.mybatis02.dao.StudentMapper"></mapper>
    </mappers>
</configuration>

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置(settings)和属性(properties)信息。文档的顶层结构如下::

  1. configuration 配置

二、MyBatis配置文件详解

该配置文件的官方详细描述可以点击这里打开

2.1、properties属性

作用:将数据连接单独配置在db.properties中,只需要在myBatisConfig.xml中加载db.properties的属性值,在myBatisConfig.xml中就不需要对数据库连接参数进行硬编码。数据库连接参数只配置在db.properties中,方便对参数进行统一管理,其它xml可以引用该db.properties。

db.properties的内容:

##MySQL连接字符串
#驱动
mysql.driver=com.mysql.jdbc.Driver
#地址
mysql.url=jdbc:mysql://127.0.0.1:3306/nfmall?useUnicode=true&amp;characterEncoding=UTF-8
#用户名
mysql.username=root
#密码
mysql.password=uchr@123

在myBatisConfig.xml中加载db.properties

<?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>
    <!--导入db.properties文件中的所有key-value数据-->
    <properties resource="db.properties">
        <!--定义一个名称为driver,值为com.mysql.jdbc.Driver的属性-->
        <property name="driver" value="com.mysql.jdbc.Driver"></property>
    </properties>
    <!--环境配置,default为默认选择的环境-->
    <environments default="work">
        <!--开发-->
        <environment id="development">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <!--连接池-->
            <dataSource type="POOLED">
                <!--引用属性${mysql.driver}-->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
        <!--运行-->
        <environment id="work">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/nfmall?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper resource="mapper/studentMapper.xml"/>-->
        <mapper class="com.zhangguo.mybatis02.dao.StudentMapper"></mapper>
    </mappers>
</configuration>

properties特性:

注意:

  • 在properties元素体内定义的属性优先读取。
  • 然后读取properties元素中resource或url加载的属性,它会覆盖已读取的同名属性。
  • 最后读取parameterType传递的属性,它会覆盖已读取的同名属性

建议:

  不要在properties元素体内添加任何属性值,只将属性值定义在properties文件中。

  在properties文件中定义属性名要有一定的特殊性,如xxxx.xxxx(jdbc.driver)

2.2、settings全局参数配置

mybatis框架运行时可以调整一些运行参数。比如,开启二级缓存,开启延迟加载等等。全局参数会影响mybatis的运行行为。

mybatis-settings的配置属性以及描述

官方文档settings的例子:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHPMyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP
<setting name="cacheEnabled" value="true"/>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="multipleResultSetsEnabled" value="true"/>
    <setting name="useColumnLabel" value="true"/>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="autoMappingBehavior" value="PARTIAL"/>
    <setting name="defaultExecutorType" value="SIMPLE"/>
    <setting name="defaultStatementTimeout" value="25"/>
    <setting name="safeRowBoundsEnabled" value="false"/>
    <setting name="mapUnderscoreToCamelCase" value="false"/>
    <setting name="localCacheScope" value="SESSION"/>
    <setting name="jdbcTypeForNull" value="OTHER"/>
    <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
View Code

示例:

这里设置MyBatis的日志输出到控制台:

    <!--外部引入的内容将覆盖内部定义的-->
    <properties resource="db.properties">
        <!--定义一个名称为driver,值为com.mysql.jdbc.Driver的属性-->
        <property name="mysql.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

结果:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

2.3、typeAiases(别名)

mapper.xml中,定义很多的statementstatement需要parameterType指定输入参数的类型、需要resultType指定输出结果的映射类型。

如果在指定类型时输入类型全路径,不方便进行开发,可以针对parameterTyperesultType指定的类型定义一些别名,在mapper.xml中通过别名定义,方便开发。

如下所示类型com.zhangguo.mybatis02.entities.Student会反复出现,冗余:

<?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.zhangguo.mybatis02.mapper.studentMapper">
    <select id="selectStudentById" resultType="com.zhangguo.mybatis02.entities.Student">
        SELECT id,name,sex from student where id=#{id}
    </select>

    <select id="selectStudentsByName" parameterType="String" resultType="com.zhangguo.mybatis02.entities.Student">
      SELECT id,name,sex from student where name like '%${value}%';
    </select>

    <insert id="insertStudent" parameterType="com.zhangguo.mybatis02.entities.Student">
        insert into student(name,sex) VALUES(#{name},'${sex}')
    </insert>

    <update id="updateStudent" parameterType="com.zhangguo.mybatis02.entities.Student">
        update student set name=#{name},sex=#{sex} where id=#{id}
    </update>

    <delete id="deleteStudent" parameterType="int">
        delete from student where id=#{id}
    </delete>

</mapper>

2.3.1.MyBatis默认支持的别名

2.3.2.自定义别名

(一)、单个别名定义(在myBatisConfig.xml)  

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <!--定义单个别名,指定名称为student,对应的类型为com.zhangguo.mybatis02.entities.Student-->
        <typeAlias type="com.zhangguo.mybatis02.entities.Student" alias="student"></typeAlias>
    </typeAliases>

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="com.zhangguo.mybatis02.mapper.studentMapper">
    <select id="selectStudentById" resultType="student">
        SELECT id,name,sex from student where id=#{id}
    </select>

    <select id="selectStudentsByName" parameterType="String" resultType="student">
      SELECT id,name,sex from student where name like '%${value}%';
    </select>

    <insert id="insertStudent" parameterType="student">
        insert into student(name,sex) VALUES(#{name},'${sex}')
    </insert>

    <update id="updateStudent" parameterType="student">
        update student set name=#{name},sex=#{sex} where id=#{id}
    </update>

    <delete id="deleteStudent" parameterType="int">
        delete from student where id=#{id}
    </delete>

</mapper>

(二)批量定义别名,扫描指定的包

定义单个别名的缺点很明显,如果项目中有很多别名则需要一个一个定义,且修改类型了还要修改配置文件非常麻烦,可以指定一个包,将下面所有的类都按照一定的规则定义成别名:

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <!--定义单个别名,指定名称为student,对应的类型为com.zhangguo.mybatis02.entities.Student-->
        <!--<typeAlias type="com.zhangguo.mybatis02.entities.Student" alias="student"></typeAlias>-->
        <!--指定包名下所有的类被自动扫描并定义默认别名,
        mybatis会自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
        <package name="com.zhangguo.mybatis02.entities"></package>
    </typeAliases>

 如果com.zhangguo.mybatis02.entities包下有一个名为Student的类,则使用别名时可以是:student,或Student。

你一定会想到当两个名称相同时的冲突问题,可以使用注解解决

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

解决方法:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

2.4、typeHandlers(类型处理器)

mybatis中通过typeHandlers完成jdbc类型和java类型的转换。

通常情况下,mybatis提供的类型处理器满足日常需要,不需要自定义.

mybatis支持类型处理器:

2.5、mappers(映射配置)

映射配置可以有多种方式,如下XML配置所示:

<!-- 将sql映射注册到全局配置中-->
    <mappers>

        <!--
            mapper 单个注册(mapper如果多的话,不太可能用这种方式)
                resource:引用类路径下的文件
                url:引用磁盘路径下的资源
                class,引用接口
            package 批量注册(基本上使用这种方式)
                name:mapper接口与mapper.xml所在的包名
        -->

        <!-- 第一种:注册sql映射文件-->
        <mapper resource="com/zhangguo/mapper/UserMapper.xml" />

        <!-- 第二种:注册接口sql映射文件必须与接口同名,并且放在同一目录下-->
        <mapper class="com.zhangguo.mapper.UserMapper" />

        <!-- 第三种:注册基于注解的接口  基于注解   没有sql映射文件,所有的sql都是利用注解写在接口上-->
        <mapper class="com.zhangguo.mapper.TeacherMapper" />

        <!-- 第四种:批量注册  需要将sql配置文件和接口放到同一目录下-->
        <package name="com.zhangguo.mapper" />

    </mappers>

2.5.1、通过resource加载单个映射文件

    <mappers>
        <!--根据路径注册一个基于XML的映射器-->
        <mapper resource="mapper/studentMapper.xml"/>
    </mappers>

注意位置

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

2.5.2:通过mapper接口加载单个映射文件

    <!-- 通过mapper接口加载单个映射配置文件
            遵循一定的规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中;
            上边规范的前提是:使用的是mapper代理方法;
      -->
         <mapper class="com.mybatis.mapper.UserMapper"/> 

按照上边的规范,将mapper.javamapper.xml放在一个目录 ,且同名。

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

注意:

对于Maven项目,IntelliJ IDEA默认是不处理src/main/java中的非java文件的,不专门在pom.xml中配置<resources>是会报错的,参考处理办法:

<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
</resources>

所以src/main/java中最好不要出现非java文件。实际上,将mapper.xml放在src/main/resources中比较合适。

2.5.3、批量加载mapper

<!-- 批量加载映射配置文件,mybatis自动扫描包下面的mapper接口进行加载
     遵循一定的规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中;
     上边规范的前提是:使用的是mapper代理方法;
      -->
<package name="com.mybatis.mapper"/> 

最后的配置文件:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHPMyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP
<?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>
    <!--导入db.properties文件中的所有key-value数据-->
    <!--外部引入的内容将覆盖内部定义的-->
    <properties resource="db.properties">
        <!--定义一个名称为driver,值为com.mysql.jdbc.Driver的属性-->
        <property name="mysql.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <!--定义单个别名,指定名称为student,对应的类型为com.zhangguo.mybatis02.entities.Student-->
        <!--<typeAlias type="com.zhangguo.mybatis02.entities.Student" alias="student"></typeAlias>-->
        <!--指定包名下所有的类被自动扫描并定义默认别名,
        mybatis会自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
        <package name="com.zhangguo.mybatis02.entities"></package>
    </typeAliases>

    <!--注册自定义的类型处理器-->
    <typeHandlers>
        <!--<typeHandler handler="" javaType="" jdbcType=""></typeHandler>-->
    </typeHandlers>

    <!--环境配置,default为默认选择的环境-->
    <environments default="development">
        <!--开发-->
        <environment id="development">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <!--连接池-->
            <dataSource type="POOLED">
                <!--引用属性${mysql.driver}-->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
        <!--运行-->
        <environment id="work">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/nfmall?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--根据路径注册一个基于XML的映射器-->
        <mapper resource="mapper/studentMapper.xml"/>
        <!--根据类型注册一个基于注解的映射器,接口-->
        <mapper class="com.zhangguo.mybatis02.dao.StudentMapper"></mapper>
        <!--根据包名批量注册包下所有基于注解的映射器-->
        <package name="com.zhangguo.mybatis02.dao"></package>
    </mappers>

</configuration>
View Code

三、使用接口+XML实现完整数据访问

上一章中使用XML作为映射器与使用接口加注解的形式分别实现了完整的数据访问,可以点击《MyBatis学习总结(一)——ORM概要与MyBatis快速起步》查看,这里综合两种方式实现数据访问,各取所长,配置灵活,在代码中不需要引用很长的id名称,面向接口编程,示例如下:

3.1、在IDEA中创建一个Maven项目

创建成功的目录结构如下:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

3.2、添加依赖

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.zhangguo.mybatis03</groupId>
    <artifactId>MyBatis03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--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.38</version>
        </dependency>
        <!-- JUnit单元测试工具 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

添加成功效果如下:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

3.3、创建POJO类

学生POJO类如下:

package com.zhangguo.mybatis03.entities;

/**
 * 学生实体
 */
public class Student {
    private int id;
    private String name;
    private String sex;

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

3.4、创建数据访问接口

StudentMapper.java:

package com.zhangguo.mybatis03.dao;

import com.zhangguo.mybatis03.entities.Student;

import java.util.List;

public interface StudentMapper {
    /**
     * 根据学生编号获得学生对象
     */
    Student selectStudentById(int id);

    /**
     * 根据学生姓名获得学生集合
     */
    List<Student> selectStudentsByName(String name);

    /**
     * 添加学生
     */
    int insertStudent(Student entity);

    /**
     * 更新学生
     */
    int updateStudent(Student entity);

    /**
     * 删除学生
     */
    int deleteStudent(int id);
}

3.5、根据接口编写XML映射器

要求方法名与Id同名,包名与namespace同名。

在src/main/resources/mapper目录下创建studentMapper.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.zhangguo.mybatis03.dao.StudentMapper">
    <select id="selectStudentById" resultType="Student">
        SELECT id,name,sex from student where id=#{id}
    </select>

    <select id="selectStudentsByName" parameterType="String" resultType="student">
        SELECT id,name,sex from student where name like '%${value}%';
    </select>

    <insert id="insertStudent" parameterType="student">
        insert into student(name,sex) VALUES(#{name},'${sex}')
    </insert>

    <update id="updateStudent" parameterType="student">
        update student set name=#{name},sex=#{sex} where id=#{id}
    </update>

    <delete id="deleteStudent" parameterType="int">
        delete from student where id=#{id}
    </delete>

</mapper>

3.6、添加MyBatis核心配置文件

在src/main/resources目录下创建两个配置文件。

mybatisCfg.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>
    <!--导入db.properties文件中的所有key-value数据-->
    <!--外部引入的内容将覆盖内部定义的-->
    <properties resource="db.properties">
        <!--定义一个名称为driver,值为com.mysql.jdbc.Driver的属性-->
        <property name="mysql.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <!--定义单个别名,指定名称为student,对应的类型为com.zhangguo.mybatis02.entities.Student-->
        <!--<typeAlias type="com.zhangguo.mybatis02.entities.Student" alias="student"></typeAlias>-->
        <!--指定包名下所有的类被自动扫描并定义默认别名,
        mybatis会自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
        <package name="com.zhangguo.mybatis03.entities"></package>
    </typeAliases>

    <!--注册自定义的类型处理器-->
    <typeHandlers>
        <!--<typeHandler handler="" javaType="" jdbcType=""></typeHandler>-->
    </typeHandlers>

    <!--环境配置,default为默认选择的环境-->
    <environments default="development">
        <!--开发-->
        <environment id="development">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <!--连接池-->
            <dataSource type="POOLED">
                <!--引用属性${mysql.driver}-->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
        <!--运行-->
        <environment id="work">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/nfmall?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--根据路径注册一个基于XML的映射器-->
        <mapper resource="mapper/studentMapper.xml"/>
    </mappers>

</configuration>

db.properties文件内容如下:

##MySQL连接字符串
#驱动
mysql.driver=com.mysql.jdbc.Driver
#地址
mysql.url=jdbc:mysql://127.0.0.1:3306/nfmall?useUnicode=true&characterEncoding=UTF-8
#用户名
mysql.username=root
#密码
mysql.password=uchr@123

3.7、编写MyBatis通用的工具类

 SqlSessionFactoryUtil.java内容如下:

package com.zhangguo.mybatis03.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatis 会话工具类
 * */
public class SqlSessionFactoryUtil {

    /**
     * 获得会话工厂
     *
     * */
    public static SqlSessionFactory getFactory(){
        InputStream inputStream = null;
        SqlSessionFactory sqlSessionFactory=null;
        try{
            //加载mybatisCfg.xml配置文件,转换成输入流
            inputStream = SqlSessionFactoryUtil.class.getClassLoader().getResourceAsStream("mybatisCfg.xml");

            //根据配置文件的输入流构造一个SQL会话工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sqlSessionFactory;
    }

    /**
     * 获得sql会话,是否自动提交
     * */
    public static SqlSession openSession(boolean isAutoCommit){
        return getFactory().openSession(isAutoCommit);
    }

    /**
     * 关闭会话
     * */
    public static void closeSession(SqlSession session){
        if(session!=null){
            session.close();
        }
    }

}

3.8、通过MyBatis实现数据访问

StudentDao.java内容如下:

package com.zhangguo.mybatis03.dao;

import com.zhangguo.mybatis03.entities.Student;
import com.zhangguo.mybatis03.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDao implements StudentMapper {

    /**
     * 根据学生编号获得学生对象
     */
    public Student selectStudentById(int id) {
        Student entity = null;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

        //获得一个映射器
        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //查询单个对象,指定参数为3
        entity = mapper.selectStudentById(id);

        //关闭
        SqlSessionFactoryUtil.closeSession(session);

        return entity;
    }


    /**
     * 根据学生姓名获得学生集合
     */
    public List<Student> selectStudentsByName(String name) {
        List<Student> entities = null;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

        //获得一个映射器
        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //查询多个对象,指定参数
        entities =mapper.selectStudentsByName(name);
        //关闭
        SqlSessionFactoryUtil.closeSession(session);
        return entities;
    }


    /**
     * 添加学生
     */
    public int insertStudent(Student entity) {
        //影响行数
        int rows=0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

        //获得一个映射器
        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //执行添加
        rows = mapper.insertStudent(entity);
        //关闭
        SqlSessionFactoryUtil.closeSession(session);
        return rows;
    }

    /**
     * 更新学生
     */
    public int updateStudent(Student entity) {
        //影响行数
        int rows=0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

        //获得一个映射器
        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //执行更新
        rows =mapper.updateStudent(entity);
        //关闭
        SqlSessionFactoryUtil.closeSession(session);
        return rows;
    }

    /**
     * 删除学生
     */
    public int deleteStudent(int id) {
        //影响行数
        int rows=0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

        //获得一个映射器
        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //执行删除
        rows = mapper.deleteStudent(id);
        //关闭
        SqlSessionFactoryUtil.closeSession(session);
        return rows;
    }

}

最后完成的项目结构:

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP

3.9、测试用例

在测试类上添加注解@FixMethodOrder(MethodSorters.JVM)的目的是指定测试方法按定义的顺序执行。

StudentDaoTest.java如下所示: 

MyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHPMyBatis学习总结(二)——MyBatis核心配置文件与输入输出映射-LMLPHP
package com.zhangguo.mybatis03.dao;import com.zhangguo.mybatis03.entities.Student;import org.junit.*;import org.junit.runners.MethodSorters;import java.util.List;/** * StudentDao Tester. * * @author <Authors name> * @version 1.0 * @since <pre>09/26/2018</pre> */@FixMethodOrder(MethodSorters.JVM)//指定测试方法按定义的顺序执行public class StudentDaoTest {    StudentMapper dao;    @Before    public void before() throws Exception {        dao=new StudentDao();    }    @After    public void after() throws
10-08 08:22