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

结果:

2.3、typeAiases(别名)

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

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

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

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangguo.mybatis02.mapper.studentMapper">
    <select id="selectStudentById" resultType="com.zhangguo.mybatis02.entities.Student">
        SELECT id,name,sex from student where id=#{id}
    </select>

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

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

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

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

</mapper>

2.3.1.MyBatis默认支持的别名

别名

映射的类型

_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>

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

UserMapper.xml引用别名

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangguo.mybatis02.mapper.studentMapper">
    <select id="selectStudentById" resultType="student">
        SELECT id,name,sex from student where id=#{id}
    </select>

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

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

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

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

</mapper>

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

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

 

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

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

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

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

解决方法:

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>

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

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

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

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

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

    </mappers>

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

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

注意位置

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

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

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

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

</configuration>
View Code

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

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

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

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

3.2、添加依赖

pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zhangguo.mybatis03</groupId>
    <artifactId>MyBatis03</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <!--MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--MySql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- JUnit单元测试工具 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

添加成功效果如下:

3.3、创建POJO类

学生POJO类如下:

package com.zhangguo.mybatis03.entities;

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

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

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

3.4、创建数据访问接口

StudentMapper.java:

package com.zhangguo.mybatis03.dao;

import com.zhangguo.mybatis03.entities.Student;

import java.util.List;

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

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

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

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

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

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

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

在src/main/resources/mapper目录下创建studentMapper.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangguo.mybatis03.dao.StudentMapper">
    <select id="selectStudentById" resultType="Student">
        SELECT id,name,sex from student where id=#{id}
    </select>

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

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

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

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

</mapper>

3.6、添加MyBatis核心配置文件

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

mybatisCfg.xml文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--导入db.properties文件中的所有key-value数据-->
    <!--外部引入的内容将覆盖内部定义的-->
    <properties resource="db.properties">
        <!--定义一个名称为driver,值为com.mysql.jdbc.Driver的属性-->
        <property name="mysql.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>

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

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

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

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

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

</configuration>

db.properties文件内容如下:

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

3.7、编写MyBatis通用的工具类

 SqlSessionFactoryUtil.java内容如下:

package com.zhangguo.mybatis03.utils;

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

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

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

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

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

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

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

}

3.8、通过MyBatis实现数据访问

StudentDao.java内容如下:

package com.zhangguo.mybatis03.dao;

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

import java.util.List;

public class StudentDao implements StudentMapper {

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

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

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

        //关闭
        SqlSessionFactoryUtil.closeSession(session);

        return entity;
    }


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

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

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


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

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

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

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

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

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

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

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

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

}

最后完成的项目结构:

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

结果:

(四)、注解参数名称:

接口:

    /**
     * 根据学生姓名或性别获得学生集合
     */
    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(1,dao.insertStudent(entity));
    }

结果:

如果要在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>
    
    <!--resultMap指定引用的映射-->
    <select id="selectStudentsBySex" parameterType="String" resultMap="stuMap">
        SELECT id,name,sex from student where sex=#{sex};
    </select>

测试结果:

(二)、使用别名

 修改映射文件:

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

    <select id="selectAllStudents" resultMap="stuKeyValueMap">
        SELECT id NAME,name VALUE from student;
    </select>

测试:

   /**
     * 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">

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

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

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

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

    <select id="selectAllStudents" resultMap="stuKeyValueMap">
        SELECT id NAME,name VALUE from student;
    </select>


    <!--定义结果映射,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>

    <!--resultMap指定引用的映射-->
    <!--<select id="selectStudentsBySex" parameterType="String" resultMap="stuMap">-->
        <!--SELECT id,name,sex from student where sex=#{sex};-->
    <!--</select>-->

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


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

    <select id="selectStudentsByIdOrSex" resultType="student">
        SELECT id,name,sex from student where id=#{no} or sex=#{sex};
    </select>


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

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

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

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

</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 {

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

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

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

        //关闭
        SqlSessionFactoryUtil.closeSession(session);

        return entity;
    }

    /**
     * 获得学生总数
     */
    public long selectStudentsCount() {
        long count = 0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

        //查询单行单列,简单值
        count = mapper.selectStudentsCount();

        //关闭
        SqlSessionFactoryUtil.closeSession(session);

        return count;
    }


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

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

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

    /**
     * 获得所有学生Map集合
     *
     */
    public List<Map<String, Object>> selectAllStudents() {
        List<Map<String, Object>> entities = null;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

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

    /**
     * 根据性别获得学生集合
     *
     * @param sex
     */
    public List<Stu> selectStudentsBySex(String sex) {
        List<Stu> entities = null;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

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

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

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

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

    /**
     * 根据学生Id或性别获得学生集合
     *
     * @param param
     */
    public List<Student> selectStudentsByIdOrSex(Map<String, Object> param) {
        List<Student> entities = null;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

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


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

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

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

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

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

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

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

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

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

    /**
     * 删除多个学生通过编号
     *
     * @param ids
     */
    public int deleteStudents(List<Integer> ids) {
        //影响行数
        int rows = 0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

        //执行删除
        rows = mapper.deleteStudents(ids);
        //关闭
        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);

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

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


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

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

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

    /**
     * 根据学生Id或性别获得学生集合
     */
    List<Student> selectStudentsByIdOrSex(Map<String,Object> param);


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

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

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

    /**
     * 删除多个学生通过编号
     */
    int deleteStudents(List<Integer> 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

posted @ 2018-10-08 08:22  张果  阅读(6445)  评论(2编辑  收藏  举报
AmazingCounters.com