MyBatis学习总结(二)——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&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        <mapper class="com.zhangguo.mybatis02.dao.StudentMapper">mapper>
    mappers>
configuration>

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

  1. configuration 配置
    • properties 属性
    • settings 设置
    • typeAliases 类型别名
    • typeHandlers 类型处理器
    • objectFactory 对象工厂
    • plugins 插件
    • environments 环境
      • environment 环境变量
        • transactionManager 事务管理器
        • dataSource 数据源
    • databaseIdProvider 数据库厂商标识
    • mappers 映射器

二、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&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>
    
    <properties resource="db.properties">
        
        <property name="driver" value="com.mysql.jdbc.Driver">property>
    properties>
    
    <environments default="work">
        
        <environment id="development">
            
            <transactionManager type="JDBC"/>
            
            <dataSource type="POOLED">
                
                <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&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="uchr@123"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        <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>

示例:

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

    
    <properties resource="db.properties">
        
        <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>
        
        <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>
        
        
        
        <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-任何兼容的字符串类型,作为代码存储(而不是索引)。

请查看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 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 ids=new ArrayList();
        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 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

接口:

    /**
     * 根据学生姓名获得学生集合
     */
    List 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 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 students=dao.selectStudentsBySex("boy");
        System.out.println(students);
        Assert.assertNotNull(students.get(0));
    }

结果:

(一)、定义并引用ResultMap

修改映射文件:

    
    <resultMap id="stuMap" type="stu">
        
        <result column="id" property="stu_id">result>
        <result column="name" property="stu_name">result>
        <result column="sex" property="stu_sex">result>
    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> 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>  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>


    
    <resultMap id="stuMap" type="stu">
        
        <result column="id" property="stu_id">result>
        <result column="name" property="stu_name">result>
        <result column="sex" property="stu_sex">result>
    resultMap>

    
    
        
    

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

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

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 selectStudentsByName(String name) {
        List 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> selectAllStudents() {
        List> 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 selectStudentsBySex(String sex) {
        List 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 selectStudentsByNameOrSex(String name, String sex) {
        List 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 selectStudentsByIdOrSex(Map param) {
        List 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 ids) {
        //影响行数
        int rows = 0;
        //打开一个会话
        SqlSession session = SqlSessionFactoryUtil.openSession(true);

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

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

}

 最终完成的接口:

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 selectStudentsByName(String name);


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

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

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

    /**
     * 根据学生Id或性别获得学生集合
     */
    List selectStudentsByIdOrSex(Map param);


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

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

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

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

 最终完成的测试:

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 
 * @version 1.0
 * @since 
09/26/2018
*/ @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 students=dao.selectStudentsByName("C"); System.out.println(students); Assert.assertNotNull(students); } /** * Method: selectAllStudents() */ @Test public void testSelectAllStudents() throws Exception { List> students=dao.selectAllStudents(); System.out.println(students); Assert.assertNotNull(students); } /** * Method: selectStudentsBySex(String sex) */ @Test public void testSelectStudentsBySex() throws Exception { List students=dao.selectStudentsBySex("boy"); System.out.println(students); Assert.assertNotNull(students.get(0)); } /** * Method: selectStudentsByIdOrSex */ @Test public void testSelectStudentsByNameOrSex() throws Exception { Map param=new HashMap(); param.put("no",1); param.put("sex","girl"); List 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 ids=new ArrayList(); ids.add(10); ids.add(11); Assert.assertEquals(2,dao.deleteStudents(ids)); } }

五、示例源代码

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