• JavaWeb-MyBatis(下)


    之前介绍了MyBatis的快速入门以及Mapper代理开发,作为一款优秀的持久层框架,就不得不探讨一下MyBatis实现的增删改查功能了,而这也是我们学习的重点和核心所在。这次通过b站黑马的品牌数据增删改查案例,来学习MyBatis实现的增删改查功能,内容如下。
    在这里插入图片描述

    一、环境准备

    1、创建tb_brand表,添加数据

    打开Navicat,连接MySQL,选择一个数据库,通过新建查询的方式创建tb_brand表,并添加数据。
    在这里插入图片描述

    对应的sql代码如下

    -- 删除tb_brand表
    drop table if exists tb_brand;
    -- 创建tb_brand表
    create table tb_brand
    (
        -- id 主键
        id           int primary key auto_increment,
        -- 品牌名称
        brand_name   varchar(20),
        -- 企业名称
        company_name varchar(20),
        -- 排序字段
        ordered      int,
        -- 描述信息
        description  varchar(100),
        -- 状态:0:禁用  1:启用
        status       int
    );
    -- 添加数据
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
           ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
           ('小米', '小米科技有限公司', 50, 'are you ok', 1);
    
    SELECT * FROM tb_brand;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    2、编写实体类 Brand

    新建一个mybatis-demo1的Maven项目,pom.xml里的坐标信息只需要将上次的复制过来就行。在其java目录下创建一个Brand实体类(com.itweb.pojo.Brand)

    package com.itweb.pojo;
    /**
     * alt + 鼠标左键:整列编辑
     * 在实体类中,基本数据类型建议使用其对应的包装类型
     */
    public class Brand {
        // id 主键
        private Integer id;
        // 品牌名称
        private String brandName;
        // 企业名称
        private String companyName;
        // 排序字段
        private Integer ordered;
        // 描述信息
        private String description;
        // 状态:0:禁用  1:启用
        private Integer status;
    
        // 提供get、set方法(鼠标右键快捷生成)
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getBrandName() {
            return brandName;
        }
        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }
        public String getCompanyName() {
            return companyName;
        }
        public void setCompanyName(String companyName) {
            this.companyName = companyName;
        }
        public Integer getOrdered() {
            return ordered;
        }
        public void setOrdered(Integer ordered) {
            this.ordered = ordered;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public Integer getStatus() {
            return status;
        }
        public void setStatus(Integer status) {
            this.status = status;
        }
        // 提供重写toString方法(鼠标右键快捷生成)
        @Override
        public String toString() {
            return "Brand{" +
                    "id=" + id +
                    ", brandName='" + brandName + '\'' +
                    ", companyName='" + companyName + '\'' +
                    ", ordered=" + ordered +
                    ", description='" + description + '\'' +
                    ", status=" + status +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    3、准备测试用例

    在项目的 test目录下创建一个MyBatisTest的测试类(com.itweb.test.MyBatisTest),如下
    在这里插入图片描述

    4、安装MyBatisX插件

    MybatisX是一款基于IDEA的快速开发插件,为效率而生。
    主要功能:
    1)XML和接口方法相互跳转
    2)根据接口方法生成statement
    安装步骤:
    File->settings->Plugins,搜索MybatisX,点击install安装即可,如下。
    在这里插入图片描述

    二、查询功能

    1、查询所有数据

    1.1 实现步骤

    1)编写接口方法Mapper接口)

    参数:无
    结果:List

    在java目录下创建一个BrandMapper接口(com.itweb.mapper.BrandMapper),代码如下

    package com.itweb.mapper;
    
    import com.itweb.pojo.Brand;
    import java.util.List;
    
    public interface BrandMapper {
        /**
         * 查询所有
         */
        public List<Brand> selectAll();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2)编写SQL语句(SQL映射文件)
    在resources目录下创建一个mapper目录(com/itweb/mapper),并在该目录下创建一个BrandMapper.xml文件。同时直接在resources目录下复制之前用到的logback.xml和mybatis-config.xml文件。

    注:在resources目录下创建分层的包要用 / 而不是 .

    在这里插入图片描述
    在这里插入图片描述

    BrandMapper映射文件里的代码如下

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.itweb.mapper.BrandMapper">
    
        <select id="selectAll" resultType="com.itweb.pojo.Brand">
            select * from tb_brand;
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3)编写测试用例并执行方法
    在之前准备好的MyBatisTest的测试类下,编写如下代码

    package com.itweb.test;
    
    import com.itweb.mapper.BrandMapper;
    import com.itweb.pojo.Brand;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class MyBatisTest {
        @Test
        public void testSelectAll() throws IOException {
            // 1.加载核心配置文件,获取 SqlSessionFactory 对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
            // 2.获取SqlSession对象,用来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
    
            // 3.1 通过SqlSession的getMapper方法获取Mapper接口的代理对象
            BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
            // 3.2 调用对应方法完成sql的执行
            List<Brand> brands = brandMapper.selectAll();
            System.out.println(brands);
    
            // 4.释放资源
            sqlSession.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    执行方法,结果如下,虽然成功查询出了所有数据,但是存在字段为null的问题,这是由于实体类的属性名与数据库表的列名不一致造成的。
    在这里插入图片描述

    4)解决属性名与列名不一致问题
    在BrandMapper.xml映射文件中做相应的修改。
    法1:

    起别名,对不一样的类名起别名,别名与实体类属性名一样。缺点是每次查询都要定义一次别名。解决方案 => 定义 sql片段,提高复用性(但该方法又有不灵活的缺点)。

    
        <sql id="brand_column">
             id, brand_name as brandName, company_name as companyName, ordered, description, status
         sql>
    
         <select id="selectAll" resultType="com.itweb.pojo.Brand">
             select
                 <include refid="brand_column" />
             from tb_brand;
         select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    法2:resultMap(最常用)
    (1)定义标签
    (2)在