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

目录

在上一章中我们学习了《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 的配置属性以及描述

setting(设置) Description(描述) valid Values(验证值组) Default(默认值)
cacheEnabled 在全局范围内启用或禁用缓存配置 任何映射器在此配置下。 true | false TRUE
lazyLoadingEnabled 在全局范围内启用或禁用延迟加载。禁用时,所有相关联的将热加载。 true | false TRUE
aggressiveLazyLoading 启用时,有延迟加载属性的对象将被完全加载后调用懒惰的任何属性。否则,每一个属性是按需加载。 true | false TRUE
multipleResultSetsEnabled 允许或不允许从一个单独的语句(需要兼容的驱动程序)要返回多个结果集。 true | false TRUE
useColumnLabel 使用列标签,而不是列名。在这方面,不同的驱动有不同的行为。参考驱动文档或测试两种方法来决定你的驱动程序的行为如何。 true | false TRUE
useGeneratedKeys 允许 JDBC 支持生成的密钥。兼容的驱动程序是必需的。此设置强制生成的键被使用,如果设置为 true,一些驱动会不兼容性,但仍然可以工作。 true | false FALSE
autoMappingBehavior 指定 MyBatis 的应如何自动映射列到字段 / 属性。NONE 自动映射。 PARTIAL 只会自动映射结果没有嵌套结果映射定义里面。 FULL 会自动映射的结果映射任何复杂的(包含嵌套或其他)。

NONE,PARTIAL,FULL

PARTIAL
defaultExecutorType 配置默认执行人。SIMPLE 执行人确实没有什么特别的。 REUSE 执行器重用准备好的语句。 BATCH 执行器重用语句和批处理更新。

SIMPLE,REUSE,BATCH

SIMPLE
safeRowBoundsEnabled 允许使用嵌套的语句 RowBounds。 true | false FALSE
mapUnderscoreToCamelCase 从经典的数据库列名 A_COLUMN 启用自动映射到骆驼标识的经典的 Java 属性名 aColumn。 true | false FALSE
localCacheScope MyBatis 的使用本地缓存,以防止循环引用,并加快反复嵌套查询。默认情况下(SESSION)会话期间执行的所有查询缓存。如果 localCacheScope=STATMENT 本地会话将被用于语句的执行,只是没有将数据共享之间的两个不同的调用相同的 SqlSession。

SESSION

STATEMENT

SESSION
dbcTypeForNull 指定为空值时,没有特定的 JDBC 类型的参数的 JDBC 类型。有些驱动需要指定列的 JDBC 类型,但其他像 NULL,VARCHAR 或 OTHER 的工作与通用值。 JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER OTHER
lazyLoadTriggerMethods 指定触发延迟加载的对象的方法。 A method name list separated by commas equals,clone,hashCode,toString
defaultScriptingLanguage 指定所使用的语言默认为动态 SQL 生成。 A type alias or fully qualified class name.

org.apache.ibatis.scripting.xmltags

.XMLDynamicLanguageDriver

callSettersOnNulls 指定如果 setter 方法或 map 的 put 方法时,将调用检索到的值是 null。它是有用的,当你依靠 Map.keySet()或 null 初始化。注意(如整型,布尔等)不会被设置为 null。 true | false FALSE
logPrefix 指定的前缀字串,MyBatis 将会增加记录器的名称。 Any String Not set
logImpl 指定 MyBatis 的日志实现使用。如果此设置是不存在的记录的实施将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
proxyFactory 指定代理工具,MyBatis 将会使用创建懒加载能力的对象。 CGLIB | JAVASSIST  CGLIB

官方文档 settings 的例子:

<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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置是否允许缓存</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="cacheEnabled"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="true"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置日志输出的目标</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="logImpl"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="STDOUT_LOGGING"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span></pre>

结果:

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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByName"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.entities.Student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
  SELECT id,name,sex from student where name like '%${value}%';
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">insert </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="insertStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.entities.Student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    insert into student(name,sex) VALUES(#{name},'${sex}')
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">insert</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">update </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="updateStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.entities.Student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    update student set name=#{name},sex=#{sex} where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">update</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">delete </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="deleteStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="int"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    delete from student where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">delete</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</mapper>

2.3.1.MyBatis 默认支持的别名

别名

映射的类型

_byte 

byte 

_long 

long 

_short 

short 

_int 

int 

_integer 

int 

_double 

double 

_float 

float 

_boolean 

boolean 

string 

String 

byte 

Byte 

long 

Long 

short 

Short 

int 

Integer 

integer 

Integer 

double 

Double 

float 

Float 

boolean 

Boolean 

date 

Date 

decimal 

BigDecimal 

bigdecimal 

BigDecimal 

2.3.2. 自定义别名

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

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">别名</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">typeAliases</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<!--定义单个别名,指定名称为 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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByName"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><strong> resultType<span style="color: rgba(0, 0, 255, 1)">="student"</span></strong><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
  SELECT id,name,sex from student where name like '%${value}%';
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">insert </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="insertStudent"</span><strong><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span></strong><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    insert into student(name,sex) VALUES(#{name},'${sex}')
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">insert</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">update </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="updateStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    update student set name=#{name},sex=#{sex} where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">update</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">delete </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="deleteStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="int"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    delete from student where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">delete</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</mapper>

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

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

 

    <settings>
        <!--设置是否允许缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--设置日志输出的目标-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">别名</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">typeAliases</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">定义单个别名,指定名称为student,对应的类型为com.zhangguo.mybatis02.entities.Student</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">&lt;typeAlias type="com.zhangguo.mybatis02.entities.Student" alias="student"&gt;&lt;/typeAlias&gt;</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">指定包名下所有的类被自动扫描并定义默认别名,
    mybatis会自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大写或小写都可以)</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">package </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.entities"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">package</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">typeAliases</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span></pre>

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

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

解决方法:

2.4、typeHandlers(类型处理器)

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

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

mybatis支持类型处理器:

类型处理器

Java 类型

JDBC 类型

BooleanTypeHandler 

Boolean,boolean 

任何兼容的布尔值

ByteTypeHandler 

Byte,byte 

任何兼容的数字或字节类型

ShortTypeHandler 

Short,short 

任何兼容的数字或短整型

IntegerTypeHandler 

Integer,int 

任何兼容的数字和整型

LongTypeHandler 

Long,long 

任何兼容的数字或长整型

FloatTypeHandler 

Float,float 

任何兼容的数字或单精度浮点型

DoubleTypeHandler 

Double,double 

任何兼容的数字或双精度浮点型

BigDecimalTypeHandler 

BigDecimal 

任何兼容的数字或十进制小数类型

StringTypeHandler 

String 

CHAR 和 VARCHAR 类型

ClobTypeHandler 

String 

CLOB 和 LONGVARCHAR 类型

NStringTypeHandler 

String 

NVARCHAR 和 NCHAR 类型

NClobTypeHandler 

String 

NCLOB 类型

ByteArrayTypeHandler 

byte[] 

任何兼容的字节流类型

BlobTypeHandler 

byte[] 

BLOB 和 LONGVARBINARY 类型

DateTypeHandler 

Date(java.util)

TIMESTAMP 类型

DateOnlyTypeHandler 

Date(java.util)

DATE 类型

TimeOnlyTypeHandler 

Date(java.util)

TIME 类型

SqlTimestampTypeHandler 

Timestamp(java.sql)

TIMESTAMP 类型

SqlDateTypeHandler 

Date(java.sql)

DATE 类型

SqlTimeTypeHandler 

Time(java.sql)

TIME 类型

ObjectTypeHandler 

任意

其他或未指定类型

EnumTypeHandler 

Enumeration 类型

VARCHAR- 任何兼容的字符串类型,作为代码存储(而不是索引)。

2.5、mappers(映射配置)

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

<!-- 将 sql 映射注册到全局配置中-->
    <mappers>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">
        mapper 单个注册(mapper如果多的话,不太可能用这种方式)
            resource:引用类路径下的文件
            url:引用磁盘路径下的资源
            class,引用接口
        package 批量注册(基本上使用这种方式)
            name:mapper接口与mapper.xml所在的包名
    </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>

    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 第一种:注册sql映射文件</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">resource</span><span style="color: rgba(0, 0, 255, 1)">="com/zhangguo/mapper/UserMapper.xml"</span> <span style="color: rgba(0, 0, 255, 1)">/&gt;</span>

    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 第二种:注册接口sql映射文件必须与接口同名,并且放在同一目录下</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">class</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mapper.UserMapper"</span> <span style="color: rgba(0, 0, 255, 1)">/&gt;</span>

    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 第三种:注册基于注解的接口  基于注解   没有sql映射文件,所有的sql都是利用注解写在接口上</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">class</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mapper.TeacherMapper"</span> <span style="color: rgba(0, 0, 255, 1)">/&gt;</span>

    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 第四种:批量注册  需要将sql配置文件和接口放到同一目录下</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">package </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mapper"</span> <span style="color: rgba(0, 0, 255, 1)">/&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span></pre>

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

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

注意位置

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

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

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

注意:

对于 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"/> 

最后的配置文件:

<?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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置是否允许缓存</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="cacheEnabled"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="true"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置日志输出的目标</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="logImpl"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="STDOUT_LOGGING"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

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

<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">注册自定义的类型处理器</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">typeHandlers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">&lt;typeHandler handler="" javaType="" jdbcType=""&gt;&lt;/typeHandler&gt;</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">typeHandlers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

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

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">根据路径注册一个基于XML的映射器</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">resource</span><span style="color: rgba(0, 0, 255, 1)">="mapper/studentMapper.xml"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">根据类型注册一个基于注解的映射器,接口</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">class</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.dao.StudentMapper"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">mapper</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">根据包名批量注册包下所有基于注解的映射器</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">package </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="com.zhangguo.mybatis02.dao"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">package</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</configuration>

View Code

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

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

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

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

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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>com.zhangguo.mybatis03<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>MyBatis03<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>1.0-SNAPSHOT<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dependencies</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">MyBatis </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>org.mybatis<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>mybatis<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>3.4.6<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">MySql数据库驱动 </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>mysql<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>mysql-connector-java<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>5.1.38<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> JUnit单元测试工具 </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>junit<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>junit<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>4.11<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">version</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">scope</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>test<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">scope</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dependencies</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</project>

添加成功效果如下:

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

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Student&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsByName(String name);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 添加学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertStudent(Student entity);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 更新学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateStudent(Student entity);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudent(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> 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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByName"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id,name,sex from student where name like '%${value}%';
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">insert </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="insertStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    insert into student(name,sex) VALUES(#{name},'${sex}')
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">insert</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">update </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="updateStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    update student set name=#{name},sex=#{sex} where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">update</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">delete </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="deleteStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="int"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    delete from student where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">delete</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</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>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置是否允许缓存</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="cacheEnabled"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="true"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">设置日志输出的目标</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">setting </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="logImpl"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="STDOUT_LOGGING"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">settings</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

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

<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">注册自定义的类型处理器</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">typeHandlers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">&lt;typeHandler handler="" javaType="" jdbcType=""&gt;&lt;/typeHandler&gt;</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">typeHandlers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

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

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">根据路径注册一个基于XML的映射器</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">resource</span><span style="color: rgba(0, 0, 255, 1)">="mapper/studentMapper.xml"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</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");

       </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">根据配置文件的输入流构造一个SQL会话工厂</span>
       sqlSessionFactory = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> 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 {

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生编号获得学生对象
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> Student selectStudentById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    Student entity </span>= <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper=session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询单个对象,指定参数为3</span>
    entity =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentById(id);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);

    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> entity;
}


</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Student&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsByName(String name) {
    List</span>&lt;Student&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper=session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)">mapper.selectStudentsByName(name);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 添加学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertStudent(Student entity) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows=0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper=session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行添加</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.insertStudent(entity);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 更新学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateStudent(Student entity) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows=0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper=session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新</span>
    rows =<span style="color: rgba(0, 0, 0, 1)">mapper.updateStudent(entity);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudent(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows=0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper=session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行删除</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.deleteStudent(id);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

}

最后完成的项目结构:

3.9、测试用例

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

StudentDaoTest.java 如下所示: 

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 Exception {
    }

    /**

    • Method: selectStudentById(int id)
      */
      @Test
      public void testSelectStudentById() throws Exception {
      Student entity
      =dao.selectStudentById(1);
      System.out.println(entity);
      Assert.assertNotNull(entity);
      }

    /**

    • Method: selectStudentsByName(String name)
      */
      @Test
      public void testSelectStudentsByName() throws Exception {
      List
      <Student> students=dao.selectStudentsByName("C");
      System.out.println(students);
      Assert.assertNotNull(students);
      }

    /**

    • Method: insertStudent
      */
      @Test
      public void testInsertStudent() throws Exception {
      Student entity
      =new Student();
      entity.setName(
      "张大");
      entity.setSex(
      "boy");

      Assert.assertEquals(1,dao.insertStudent(entity));
      }

    /**

    • Method: updateStudent
      */
      @Test
      public void testUpdateStudent() throws Exception {
      Student entity
      =dao.selectStudentById(11);
      entity.setName(
      "张丽美");
      entity.setSex(
      "girl");

      Assert.assertEquals(1,dao.updateStudent(entity));
      }

    /**

    • Method: deleteStudent
      */
      @Test
      public void testDeleteStudent() throws Exception {
      Assert.assertEquals(
      1,dao.deleteStudent(12));
      }
      }
View Code

3.10、测试结果

测试前的数据库:

测试结果:

日志:

"C:\Program Files\Java\jdk1.8.0_111\bin\java" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\lib\idea_rt.jar=2783:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\lib\idea_rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\plugins\junit\lib\junit-rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\plugins\junit\lib\junit5-rt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\rt.jar;D:\Documents\Downloads\Compressed\MyBatis03\target\test-classes;D:\Documents\Downloads\Compressed\MyBatis03\target\classes;C:\Users\Administrator\.m2\repository\org\mybatis\mybatis\3.4.6\mybatis-3.4.6.jar;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar;C:\Users\Administrator\.m2\repository\junit\junit\4.11\junit-4.11.jar;C:\Users\Administrator\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.zhangguo.mybatis03.dao.StudentDaoTest
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 662822946.
==>  Preparing: delete from student where id=? 
==> Parameters: 12(Integer)
<==    Updates: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2781e022]
Returned connection 662822946 to pool.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1045941616.
==>  Preparing: SELECT id,name,sex from student where id=? 
==> Parameters: 11(Integer)
<==    Columns: id, name, sex
<==        Row: 11, lili, secret
<==      Total: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3e57cd70]
Returned connection 1045941616 to pool.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1540270363.
==>  Preparing: update student set name=?,sex=? where id=? 
==> Parameters: 张丽美 (String), girl(String), 11(Integer)
<==    Updates: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5bcea91b]
Returned connection 1540270363 to pool.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 681384962.
==>  Preparing: insert into student(name,sex) VALUES(?,'boy') 
==> Parameters: 张大 (String)
<==    Updates: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@289d1c02]
Returned connection 681384962 to pool.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 428910174.
==>  Preparing: SELECT id,name,sex from student where name like '%C%'; 
==> Parameters: 
<==    Columns: id, name, sex
<==        Row: 4, candy, secret
<==      Total: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1990a65e]
Returned connection 428910174 to pool.
[Student{id=4, name='candy', sex='secret'}]
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1134612201.
==>  Preparing: SELECT id,name,sex from student where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, name, sex
<==        Row: 1, rose, girl
<==      Total: 1
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@43a0cee9]
Returned connection 1134612201 to pool.
Student{id=1, name='rose', sex='girl'}

Process finished with exit code 0

View Code

测试后的数据库:

 

四、MyBatis 输入输出映射

4.1、输入映射

通过 parameterType 指定输入参数的类型,类型可以是简单类型、HashMap、POJO的包装类型。

Mybatis 的配置文件中的 select,insert,update,delete 有一个属性 parameter 来接收 mapper 接口方法中的参数。可以接收的类型有简单类型和复杂类型,但是只能是一个参数。这个属性是可选的,因为 Mybatis 可以通过 TypeHandler 来判断传入的参数类型,默认值是 unset。

4.1.1、基本类型

各种 java 的基本数据类型。常用的有 int、String、Data 等

接口:

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

映射:

    <select id="selectStudentById" resultType="Student" parameterType="int">
        SELECT id,name,sex from student where id=#{id}
    </select>

测试:

    /**
     * Method: selectStudentById(int id)
     */
    @Test
    public void testSelectStudentById() throws Exception {
        Student entity=dao.selectStudentById(1);
        System.out.println(entity);
        Assert.assertNotNull(entity);
    }

结果:

用 #{变量名} 来取值,这里的变量名是任意的,可以用 value 或者是其它的什么值,这里用 id 是为了便于理解,并不存在什么对应关系的。因为 java 反射主只能够得到方法参数的类型,而无从知道参数的名字的。当在动态 sql 中的 if 语句中的 test 传递参数时,就必须要用 _parameter 来传递参数了(OGNL 表达式),如果你传入 id 就会报错。

4.1.2、多个参数

(一)、旧版本 MyBatis 使用索引号:

<select id="selectStudentsByNameOrSex" resultType="student">
    SELECT id,name,sex from student where name='%${0}%' or sex=#{1};
</select>

由于是多参数那么就不能使用 parameterType, 改用 #{index}是第几个就用第几个的索引,索引从 0 开始

注意:

如果出现错误:Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2],请使用 #{arg0} 或 #{param1}

注意:在 MyBatis3.4.4 版以后不能直接使用 #{0} 要使用 #{arg0}

(二)、新版本 MyBatis 使用索引号:

接口:

    /**
     * 根据学生姓名或性别获得学生集合
     */
    List<Student> selectStudentsByNameOrSex(String name,String sex);

映射:

<select id="selectStudentsByNameOrSex" resultType="student">
    SELECT id,name,sex from student where name like '%${arg0}%' or sex=#{param2};
</select>

方法一:arg0,arg1,arg2...
方法二:param1,param2,param3...

测试:

    /**
     * Method: selectStudentsByNameOrSex(String name, String sex)
     */
    @Test
    public void selectStudentsByNameOrSex() throws Exception {
        List<Student> students=dao.selectStudentsByNameOrSex("Candy","boy");
        System.out.println(students);
        Assert.assertNotNull(students);
    }

结果:

(三)、使用 Map

接口:

    /**
     * 根据学生姓名或性别获得学生集合
     */
    List<Student> selectStudentsByNameOrSex(Map<String,Object> params);

映射:

    <select id="selectStudentsByNameOrSex" resultType="student">
        SELECT id,name,sex from student where name like '%${name}%' or sex=#{sex};
    </select>

测试:

    /**
     * Method: List<Student> selectStudentsByNameOrSex(Map<String,Object> params);
     */
    @Test
    public void selectStudentsByNameOrSex() throws Exception {
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("name","Candy");
        params.put("sex","girl");
        List<Student> students=dao.selectStudentsByNameOrSex(params);
    System.out.println(students);
    Assert.assertNotNull(students);
}</span></pre>

结果:

(四)、注解参数名称:

接口:

    /**
     * 根据学生姓名或性别获得学生集合
     */
    List<Student> selectStudentsByNameOrSex(@Param("realname") String name,@Param("sex") String sex);

映射:

    <select id="selectStudentsByNameOrSex" resultType="student">
        SELECT id,name,sex from student where name like '%${realname}%' or sex=#{sex};
    </select>

测试:

    /**
     * Method: selectStudentsByNameOrSex(String name,String sex)
     */
    @Test
    public void testSelectStudentsByNameOrSex() throws Exception {
        List<Student> students=dao.selectStudentsByNameOrSex("C","boy");
        System.out.println(students);
        Assert.assertNotNull(students);
    }

结果:

4.1.3、POJO 对象

各种类型的 POJO,取值用 #{属性名}。这里的属性名是和传入的 POJO 中的属性名一一对应。

接口:

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

映射:

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

测试:

    /**
     * Method: insertStudent
     */
    @Test
    public void testInsertStudent() throws Exception {
        Student entity=new Student();
        entity.setName("张明");
        entity.setSex("boy");
    Assert.assertEquals(</span>1<span style="color: rgba(0, 0, 0, 1)">,dao.insertStudent(entity));
}</span></pre>

结果:

如果要在 if 元素中测试传入的 user 参数, 仍然要使用 _parameter 来引用传递进来的实际参数, 因为传递进来的 User 对象的名字是不可考的。如果测试对象的属性, 则直接引用属性名字就可以了。
测试 user 对象:

<if test="_parameter!= null">

测试 user 对象的属性:

<if test="name!= null">

如果对象中还存在对象则需要使用 ${属性名. 属性.x} 方式访问

4.1.4、Map

具体请查看 4.1.2 节

传入 map 类型, 直接通过 #{keyname} 就可以引用到键对应的值。使用 @param 注释的多个参数值也会组装成一个 map 数据结构, 和直接传递 map 进来没有区别。

mapper 接口:

int updateByExample(@Param("user") User user, @Param("example") UserExample example);

sql 映射:

<update id="updateByExample" parameterType="map" > 

update tb_user set id = #{user.id}, ...

<if test="_parameter != null" >

<include refid="Update_By_Example_Where_Clause" />

</if>

</update>

注意这里测试传递进来的 map 是否为空, 仍然使用 _parameter

4.1.5、集合类型

可以传递一个 List 或 Array 类型的对象作为参数,MyBatis 会自动的将 List 或 Array 对象包装到一个 Map 对象中,List 类型对象会使用 list 作为键名, 而 Array 对象会用 array 作为键名。集合类型通常用于构造 IN 条件,sql 映射文件中使用 foreach 元素来遍历 List 或 Array 元素。

假定这里需要实现多删除功能,示例如下:

接口:

    /**
     * 删除多个学生通过编号
     */
    int deleteStudents(List<Integer> ids);

映射:

    <delete id="deleteStudents">
        delete from student where id in
        <foreach collection="list" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

collection 这里只能是 list

测试:

    /**
     * Method: deleteStudents
     */
    @Test
    public void testDeleteStudents() throws Exception {
        List<Integer> ids=new ArrayList<Integer>();
        ids.add(10);
        ids.add(11);
        Assert.assertEquals(2,dao.deleteStudents(ids));
    }

结果:

当然查询中也可以这样使用

public List<XXXBean> getXXXBeanList(List<String> list);  

<select id="getXXXBeanList" resultType="XXBean">
  select 字段... from XXX where id in
  
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    #{item}
  
</foreach>
</select>

foreach 最后的效果是 select 字段... from XXX where id in ('1','2','3','4')

对于单独传递的 List 或 Array, 在 SQL 映射文件中映射时, 只能通过 list 或 array 来引用。但是如果对象类型有属性的类型为 List 或 Array,则在 sql 映射文件的 foreach 元素中, 可以直接使用属性名字来引用。
mapper 接口: 

List<User> selectByExample(UserExample example);

sql 映射文件: 

<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
</where>

在这里,UserExample 有一个属性叫 oredCriteria, 其类型为 List, 所以在 foreach 元素里直接用属性名 oredCriteria 引用这个 List 即可。

item="criteria" 表示使用 criteria 这个名字引用每一个集合中的每一个 List 或 Array 元素。

4.2、输出映射

输出映射主要有两种方式指定 ResultType 或 ResultMap,现在分别介绍一下:

4.2.1、ResultType

使用 ResultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。

如果查询出来的列名和 POJO中的属性名全部不一致,没有创建 POJO对象。

只要查询出来的列名和 POJO中的属性有一个一致,就会创建 POJO对象。

(一)、输出简单类型

接口:

    /**
     * 获得学生总数
     * */
    long selectStudentsCount();

映射:

    <select id="selectStudentsCount" resultType="long">
        SELECT count(*) from student
    </select>

测试:

    /**
     * Method: selectStudentsCount()
     */
    @Test
    public void testSelectStudentsCount() throws Exception {
        Assert.assertNotEquals(0,dao.selectStudentsCount());}

结果:

查询出来的结果集只有一行一列,可以使用简单类型进行输出映射。

( 二)、输出 POJO 对象和 POJO 列表 

不管是输出的POJO单个对象还是一个列表(List中存放 POJO),在mapper.xml中 ResultType指定的类型是一样的,但方法返回值类型不一样。

输出单个 POJO 对象,方法返回值是单个对象类型

接口:

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

映射:

    <select id="selectStudentById" resultType="Student">
        SELECT id,name,sex from student where id=#{id}
    </select>

输出 pojo 对象 list,方法返回值是 List<POJO>

接口:

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

映射:

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

生成的动态代理对象中是根据 mapper.java 方法的返回值类型确定是调用 selectOne(返回单个对象调用) 还是 selectList(返回集合对象调用)

4.2.2、ResultMap

MyBatis中使用 ResultMap完成自定义输出结果映射,如一对多,多对多关联关系。

问题:

假定 POJO 对象与表中的字段不一致,如下所示:

接口:

    /**
     * 根据性别获得学生集合
     */
    List<Stu> selectStudentsBySex(String sex);

映射:

    <select id="selectStudentsBySex" parameterType="String" resultType="stu">
        SELECT id,name,sex from student where sex=#{sex};
    </select>

测试:

    /**
     * Method: selectStudentsBySex(String sex)
     */
    @Test
    public void testSelectStudentsBySex() throws Exception {
        List<Stu> students=dao.selectStudentsBySex("boy");
        System.out.println(students);
        Assert.assertNotNull(students.get(0));}

结果:

 

(一)、定义并引用 ResultMap

修改映射文件:

    <!--定义结果映射,id 是引用时的编号需唯一,stu 是最终被映射的类型-->
    <resultMap id="stuMap" type="stu">
        <!--映射结果,collumn 表示列名,property 表示属性名-->
        <result column="id" property="stu_id"></result>
        <result column="name" property="stu_name"></result>
        <result column="sex" property="stu_sex"></result>
    </resultMap>
<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">resultMap指定引用的映射</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsBySex"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><span style="color: rgba(255, 0, 0, 1)"> resultMap</span><span style="color: rgba(0, 0, 255, 1)">="stuMap"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id,name,sex from student where sex=#{sex};
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span></pre>

测试结果:

(二)、使用别名

 修改映射文件:

    <select id="selectStudentsBySex" parameterType="String" resultType="stu">
      SELECT id stu_id,name stu_name,sex as stu_sex from student where sex=#{sex};
    </select>

测试结果:

4.2.3、返回 Map

假定要返回 id 作为 key,name 作为 value 的 Map。

接口:

    /**
     * 获得所有学生 Map 集合
     */
    List<Map<String,Object>> selectAllStudents();

映射:

    <resultMap id="stuKeyValueMap" type="HashMap">
        <result property="name" column="NAME"></result>
        <result property="value" column="VALUE"></result>
    </resultMap>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectAllStudents"</span><span style="color: rgba(255, 0, 0, 1)"> resultMap</span><span style="color: rgba(0, 0, 255, 1)">="stuKeyValueMap"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id NAME,name VALUE from student;
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span></pre>

测试:

   /**
     * Method: selectAllStudents()
     */
    @Test
    public void testSelectAllStudents() throws Exception {
        List<Map<String,Object>>  students=dao.selectAllStudents();
        System.out.println(students);
        Assert.assertNotNull(students);
    }

结果:

<resultMap id="pieMap"   type="HashMap">  
    <result property="value" column="VALUE" />  
    <result property="name" column="NAME" />  
</resultMap>

<select id="queryPieParam" parameterType="String" resultMap="pieMap">
SELECT
  PLAT_NAME NAME,
<if test='_parameter ==" 总量 "'>
AMOUNT VALUE
</if>
<if test='_parameter ==" 总额 "'>
TOTALS VALUE
</if>
FROM
DOMAIN_PLAT_DEAL_PIE
ORDER BY
<if test='_parameter ==" 总量 "'>
AMOUNT
</if>
<if test='_parameter ==" 总额 "'>
TOTALS
</if>
ASC
</select>

resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。

如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。

 最终完成的映射器:

<?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">
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentById"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="Student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id,name,sex from student where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsCount"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="long"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT count(*) from student
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByName"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id,name,sex from student where name like '%${value}%';
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">resultMap </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="stuKeyValueMap"</span><span style="color: rgba(255, 0, 0, 1)"> type</span><span style="color: rgba(0, 0, 255, 1)">="HashMap"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">result </span><span style="color: rgba(255, 0, 0, 1)">property</span><span style="color: rgba(0, 0, 255, 1)">="name"</span><span style="color: rgba(255, 0, 0, 1)"> column</span><span style="color: rgba(0, 0, 255, 1)">="NAME"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">result</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">result </span><span style="color: rgba(255, 0, 0, 1)">property</span><span style="color: rgba(0, 0, 255, 1)">="value"</span><span style="color: rgba(255, 0, 0, 1)"> column</span><span style="color: rgba(0, 0, 255, 1)">="VALUE"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">result</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">resultMap</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectAllStudents"</span><span style="color: rgba(255, 0, 0, 1)"> resultMap</span><span style="color: rgba(0, 0, 255, 1)">="stuKeyValueMap"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id NAME,name VALUE from student;
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>


<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">定义结果映射,id是引用时的编号需唯一,stu是最终被映射的类型</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">resultMap </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="stuMap"</span><span style="color: rgba(255, 0, 0, 1)"> type</span><span style="color: rgba(0, 0, 255, 1)">="stu"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">映射结果,collumn表示列名,property表示属性名</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">result </span><span style="color: rgba(255, 0, 0, 1)">column</span><span style="color: rgba(0, 0, 255, 1)">="id"</span><span style="color: rgba(255, 0, 0, 1)"> property</span><span style="color: rgba(0, 0, 255, 1)">="stu_id"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">result</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">result </span><span style="color: rgba(255, 0, 0, 1)">column</span><span style="color: rgba(0, 0, 255, 1)">="name"</span><span style="color: rgba(255, 0, 0, 1)"> property</span><span style="color: rgba(0, 0, 255, 1)">="stu_name"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">result</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">result </span><span style="color: rgba(255, 0, 0, 1)">column</span><span style="color: rgba(0, 0, 255, 1)">="sex"</span><span style="color: rgba(255, 0, 0, 1)"> property</span><span style="color: rgba(0, 0, 255, 1)">="stu_sex"</span><span style="color: rgba(0, 0, 255, 1)">&gt;&lt;/</span><span style="color: rgba(128, 0, 0, 1)">result</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">resultMap</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">resultMap指定引用的映射</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">&lt;select id="selectStudentsBySex" parameterType="String" resultMap="stuMap"&gt;</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">SELECT id,name,sex from student where sex=#{sex};</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)">&lt;/select&gt;</span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsBySex"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="String"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="stu"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
  SELECT id stu_id,name stu_name,sex as stu_sex from student where sex=#{sex};
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>


<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByNameOrSex"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
  SELECT id,name,sex from student where name like '%${realname}%' or sex=#{sex};
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">select </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="selectStudentsByIdOrSex"</span><span style="color: rgba(255, 0, 0, 1)"> resultType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    SELECT id,name,sex from student where id=#{no} or sex=#{sex};
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">select</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>


<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">insert </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="insertStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    insert into student(name,sex) VALUES(#{name},'${sex}')
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">insert</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">update </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="updateStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="student"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    update student set name=#{name},sex=#{sex} where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">update</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">delete </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="deleteStudent"</span><span style="color: rgba(255, 0, 0, 1)"> parameterType</span><span style="color: rgba(0, 0, 255, 1)">="int"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    delete from student where id=#{id}
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">delete</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">delete </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="deleteStudents"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    delete from student where id in
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">foreach </span><span style="color: rgba(255, 0, 0, 1)">collection</span><span style="color: rgba(0, 0, 255, 1)">="list"</span><span style="color: rgba(255, 0, 0, 1)"> item</span><span style="color: rgba(0, 0, 255, 1)">="id"</span><span style="color: rgba(255, 0, 0, 1)"> open</span><span style="color: rgba(0, 0, 255, 1)">="("</span><span style="color: rgba(255, 0, 0, 1)"> separator</span><span style="color: rgba(0, 0, 255, 1)">=","</span><span style="color: rgba(255, 0, 0, 1)"> close</span><span style="color: rgba(0, 0, 255, 1)">=")"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        #{id}
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">foreach</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">delete</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</mapper>

View Code

 最终完成的数据访问类似:

package com.zhangguo.mybatis03.dao;

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

import java.util.List;
import java.util.Map;

public class StudentDao implements StudentMapper {

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生编号获得学生对象
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> Student selectStudentById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    Student entity </span>= <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询单个对象,指定参数为3</span>
    entity =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentById(id);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);

    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> entity;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 获得学生总数
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">long</span><span style="color: rgba(0, 0, 0, 1)"> selectStudentsCount() {
    </span><span style="color: rgba(0, 0, 255, 1)">long</span> count = 0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询单行单列,简单值</span>
    count =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentsCount();

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);

    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> count;
}


</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Student&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsByName(String name) {
    List</span>&lt;Student&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentsByName(name);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 获得所有学生Map集合
 *
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Map&lt;String, Object&gt;&gt;<span style="color: rgba(0, 0, 0, 1)"> selectAllStudents() {
    List</span>&lt;Map&lt;String, Object&gt;&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectAllStudents();
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据性别获得学生集合
 *
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> sex
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Stu&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsBySex(String sex) {
    List</span>&lt;Stu&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentsBySex(sex);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名或性别获得学生集合
 *
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> name
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> sex
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Student&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsByNameOrSex(String name, String sex) {
    List</span>&lt;Student&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentsByNameOrSex(name, sex);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生Id或性别获得学生集合
 *
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> param
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Student&gt; selectStudentsByIdOrSex(Map&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)"> param) {
    List</span>&lt;Student&gt; entities = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询多个对象,指定参数</span>
    entities =<span style="color: rgba(0, 0, 0, 1)"> mapper.selectStudentsByIdOrSex(param);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return entities;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 添加学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertStudent(Student entity) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows = 0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行添加</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.insertStudent(entity);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 更新学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateStudent(Student entity) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows = 0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.updateStudent(entity);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudent(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows = 0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行删除</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.deleteStudent(id);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除多个学生通过编号
 *
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> ids
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudents(List&lt;Integer&gt;<span style="color: rgba(0, 0, 0, 1)"> ids) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">影响行数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> rows = 0<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">打开一个会话</span>
    SqlSession session = SqlSessionFactoryUtil.openSession(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获得一个映射器</span>
    StudentMapper mapper = session.getMapper(StudentMapper.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行删除</span>
    rows =<span style="color: rgba(0, 0, 0, 1)"> mapper.deleteStudents(ids);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>

SqlSessionFactoryUtil.closeSession(session);
return rows;
}

}

View Code

 最终完成的接口:

package com.zhangguo.mybatis03.dao;

import com.zhangguo.mybatis03.entities.Stu;
import com.zhangguo.mybatis03.entities.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

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

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 获得学生总数
 * </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">long</span><span style="color: rgba(0, 0, 0, 1)"> selectStudentsCount();

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Student&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsByName(String name);


</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 获得所有学生Map集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Map&lt;String,Object&gt;&gt;<span style="color: rgba(0, 0, 0, 1)"> selectAllStudents();

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据性别获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Stu&gt;<span style="color: rgba(0, 0, 0, 1)"> selectStudentsBySex(String sex);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生姓名或性别获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Student&gt; selectStudentsByNameOrSex(@Param("realname") String name,@Param("sex"<span style="color: rgba(0, 0, 0, 1)">) String sex);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 根据学生Id或性别获得学生集合
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
List</span>&lt;Student&gt; selectStudentsByIdOrSex(Map&lt;String,Object&gt;<span style="color: rgba(0, 0, 0, 1)"> param);


</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 添加学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertStudent(Student entity);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 更新学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateStudent(Student entity);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除学生
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudent(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id);

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 删除多个学生通过编号
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">int</span> deleteStudents(List&lt;Integer&gt;<span style="color: rgba(0, 0, 0, 1)"> ids);

}

View Code

 最终完成的测试:

package com.zhangguo.mybatis03.dao;

import com.zhangguo.mybatis03.entities.Stu;
import com.zhangguo.mybatis03.entities.Student;
import org.junit.*;
import org.junit.runners.MethodSorters;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**

  • 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 Exception {
    }

    /**

    • Method: selectStudentById(int id)
      */
      @Test
      public void testSelectStudentById() throws Exception {
      Student entity
      =dao.selectStudentById(1);
      System.out.println(entity);
      Assert.assertNotNull(entity);
      }

    //
    /**

    • Method: selectStudentsCount()
      */
      @Test
      public void testSelectStudentsCount() throws Exception {
      Assert.assertNotEquals(
      0,dao.selectStudentsCount());
      }
      /**
    • Method: selectStudentsByName(String name)
      */
      @Test
      public void testSelectStudentsByName() throws Exception {
      List
      <Student> students=dao.selectStudentsByName("C");
      System.out.println(students);
      Assert.assertNotNull(students);
      }

    /**

    • Method: selectAllStudents()
      */
      @Test
      public void testSelectAllStudents() throws Exception {
      List
      <Map<String,Object>> students=dao.selectAllStudents();
      System.out.println(students);
      Assert.assertNotNull(students);
      }

    /**

    • Method: selectStudentsBySex(String sex)
      */
      @Test
      public void testSelectStudentsBySex() throws Exception {
      List
      <Stu> students=dao.selectStudentsBySex("boy");
      System.out.println(students);
      Assert.assertNotNull(students.get(
      0));
      }

    /**

    • Method: selectStudentsByIdOrSex
      */
      @Test
      public void testSelectStudentsByNameOrSex() throws Exception {
      Map
      <String ,Object> param=new HashMap<String,Object>();
      param.put(
      "no",1);
      param.put(
      "sex","girl");
      List
      <Student> students=dao.selectStudentsByIdOrSex(param);
      System.out.println(students);
      Assert.assertNotNull(students);
      }

    /**

    • Method: insertStudent
      */
      @Test
      public void testInsertStudent() throws Exception {
      Student entity
      =new Student();
      //entity.setName("张明");
      entity.setSex("boy");

      Assert.assertEquals(1,dao.insertStudent(entity));
      }

    /**

    • Method: updateStudent
      */
      @Test
      public void testUpdateStudent() throws Exception {
      Student entity
      =dao.selectStudentById(11);
      //entity.setName("张丽美");
      entity.setSex("girl");

      Assert.assertEquals(1,dao.updateStudent(entity));
      }

    /**

    • Method: deleteStudent
      */
      @Test
      public void testDeleteStudent() throws Exception {
      Assert.assertEquals(
      1,dao.deleteStudent(12));
      }

    /**

    • Method: deleteStudents
      */
      @Test
      public void testDeleteStudents() throws Exception {
      List
      <Integer> ids=new ArrayList<Integer>();
      ids.add(
      10);
      ids.add(
      11);
      Assert.assertEquals(
      2,dao.deleteStudents(ids));
      }
      }
View Code

五、示例源代码

https://git.coding.net/zhangguo5/MyBatis03.git

https://git.coding.net/zhangguo5/MyBatis02.git

六、视频

https://www.bilibili.com/video/av32447485/

七、作业

1、重现上所有上课示例

2、请使用 Maven 多模块 +Git+MyBatis 完成一个单表的管理功能,需要 UI, 可以 AJAX 也可以 JSTL 作表示层。

3、分页,多条件组合查询,多表连接(选作)

4、内部测试题(4 个小时)

4.1、请实现一个简易图书管理系统(LibSystem),实现图书管理功能,要求如下:(初级)

1、管理数据库中所有图书(Books),包含图书编号(isbn)、书名(title)、作者(author)、价格(price)、出版日期(publishDate)

2、Maven 多模块 +MySQL+Git+MyBatis+JUnit 单元测试

3、表示层可以是 AJAX 或 JSTL

C10 R(10+10) U10 D10

 

4.2、请实现一个迷你图书管理系统(LibSystem),实现图书管理功能,要求如下:(中级)

1、管理数据库中所有图书分类(Categories),包含图书编号(id), 名称(name)

2、管理数据库中所有图书(Books),包含图书编号(isbn)、类别(categoryId,外键)书名(title)、作者(author)、价格(price)、出版日期(publishDate)、封面(cover)、详细介绍(details)

3、分页 10

4、多条件组件查询(3 个以上的条件任意组合)(高级) 10

5、多删除 (高级) 10

6、上传封面 (高级) 10

7、富文本编辑器 (高级) 10