主頁 > 後端開發 > MyBatis快速上手與知識點總結

MyBatis快速上手與知識點總結

2022-08-30 06:59:23 後端開發

目錄
  • 1、MyBatis概述
    • 1.1 MyBatis概述
    • 1.2 JDBC缺點
    • 1.3 MyBatis優化
  • 2、MyBatis快速入門
  • 3、Mapper代理開發
    • 3.1 Mapper代理開發概述
    • 3.2 使用Mapper代理要求
    • 3.3 案例代碼實作
  • 4、核心組態檔
    • 4.1 多環境配置
    • 4.2 型別別名
  • 5、組態檔實作CRUD
    • 5.1 環境準備
    • 5.2 查詢所有資料
    • 5.3 查詢
    • 5.4 多條件查詢
    • 5.6 添加資料與MyBatis事務
    • 5.7 修改
    • 5.8 洗掉資料
    • 5.9 MyBatis引數傳遞
  • 6、通過注解實作CRUD


閱讀提示:

本文默認已經預裝預裝maven

1、MyBatis概述

1.1 MyBatis概述

  • 持久層框架,用于簡化JDBC開發,是對JDBC的封裝

    持久層:

    • 負責將資料保存到資料庫的代碼部分
    • Java EE三層架構:表現層、業務層、持久層

1.2 JDBC缺點

  • 硬編碼,不利于維護
    • 注冊驅動、獲取連接
    • SQL陳述句
  • 操作繁瑣
    • 手動設定引數
    • 手動封裝結果集

1.3 MyBatis優化

  • 硬編碼 --> 組態檔
  • 繁瑣慚怍 --> 框架封裝自動完成

2、MyBatis快速入門

  • 需求:查詢user表中的所有資料

  • SQL

    create database mybatis;
    use mybatis;
    
    drop table if exists tb_user;
    
    create table tb_user(
    	id int primary key auto_increment,
    	username varchar(20),
    	password varchar(20),
    	gender char(1),
    	addr varchar(30)
    );
    
    INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
    INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
    INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
    
  • 代碼實作

    • 創建模塊,匯入坐標

      在pom.xml中組態檔中添加依賴的坐標

      注意:需要在專案的resources目錄下創建logback的組態檔

      <dependencies>
          <!--mybatis 依賴-->
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.5.5</version>
          </dependency>
          <!--mysql 驅動-->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.46</version>
          </dependency>
          <!--junit 單元測驗-->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.13</version>
              <scope>test</scope>
          </dependency>
          <!-- 添加slf4j日志api -->
          <dependency>
              <groupId>org.slf4j</groupId>
              <artifactId>slf4j-api</artifactId>
              <version>1.7.20</version>
          </dependency>
          <!-- 添加logback-classic依賴 -->
          <dependency>
              <groupId>ch.qos.logback</groupId>
              <artifactId>logback-classic</artifactId>
              <version>1.2.3</version>
          </dependency>
          <!-- 添加logback-core依賴 -->
          <dependency>
              <groupId>ch.qos.logback</groupId>
              <artifactId>logback-core</artifactId>
              <version>1.2.3</version>
          </dependency>
      </dependencies>
      
    • 撰寫MyBatis核心檔案

      核心檔案用于替換資訊,解決硬編碼問題

      在模塊下的resources目錄下創建mybatis的組態檔mybatis-config.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">
                  <!-- 采用JDBC的事務管理方式 -->
                  <transactionManager type="JDBC"/>
                  <!-- 資料庫連接資訊 -->
                  <dataSource type="POOLED">
                      <property name="driver" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/com.mysql.jdbc.Driver"/>
                      <property name="url" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/jdbc:mysql:///mybatis?useSSL=false"/>
                      <property name="username" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/root"/>
                      <property name="password" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/123456"/>
                  </dataSource>
              </environment>
          </environments>
          <!-- 加載SQL映射檔案 -->
          <mappers>
              <mapper resource="UserMapper.xml"/>
          </mappers>
      </configuration>
      
    • 撰寫SQL映射檔案

      SQL映射檔案用于統一管理SQL陳述句,解決硬編碼問題

      在模塊的resources目錄下創建映射組態檔UserMaooer.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">
      <!--
          namespace:命名空間
      -->
      <mapper namespace="test">
          <!-- statement -->
          <select id="selectAll" resultType="priv.dandelion.entity.User">
              select * from tb_user;
          </select>
      </mapper>
      
    • 編碼

      • 物體類

        package priv.dandelion.entity;
        
        public class User {
        
            private Integer id;
            private String username;
            private String password;
            private String gender;
            private String address;
        
            public User() {
            }
        
            public User(Integer id, String username, String password, String gender, String address) {
                this.id = id;
                this.username = username;
                this.password = password;
                this.gender = gender;
                this.address = address;
            }
        
            public Integer getId() {
                return id;
            }
        
            public void setId(Integer id) {
                this.id = id;
            }
        
            public String getUsername() {
                return username;
            }
        
            public void setUsername(String username) {
                this.username = username;
            }
        
            public String getPassword() {
                return password;
            }
        
            public void setPassword(String password) {
                this.password = password;
            }
        
            public String getGender() {
                return gender;
            }
        
            public void setGender(String gender) {
                this.gender = gender;
            }
        
            public String getAddress() {
                return address;
            }
        
            public void setAddress(String address) {
                this.address = address;
            }
        
            @Override
            public String toString() {
                return "User{" +
                        "id=" + id +
                        ", username='" + username + '\'' +
                        ", password='" + password + '\'' +
                        ", gender='" + gender + '\'' +
                        ", address='" + address + '\'' +
                        '}';
            }
        }
        
        
      • 測驗類

        public static void main(String[] args) throws IOException {
            // 加載mybatis的核心組態檔,獲取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 獲取Session物件,執行SQL陳述句
            SqlSession sqlSession = sqlSessionFactory.openSession();
            // 執行SQL,處理結果
            List<User> users = sqlSession.selectList("test.selectAll");
            System.out.println(users);
            // 釋放資源
            sqlSession.close();
        }
        

3、Mapper代理開發

3.1 Mapper代理開發概述

解決形如上述測驗類中List<User> users = sqlSession.selectList("test.selectAll");的硬編碼問題

  • 解決原生方式中的硬編碼
  • 簡化后期的SQL執行

3.2 使用Mapper代理要求

  • 定義與SQL映射檔案同名的Mapper介面,并且將Mapper介面和SQL映射檔案放置在同一目錄下

    maven專案開發時要求code和resources分開,可在resources中創建相同包檔案來是實作上述效果

  • 設定SQL映射檔案的namespace屬性未Mapper介面的全限定名

  • 在Mapper介面中定義方法,方法名就是SQL映射檔案中SQL陳述句的id,并且引數型別和回傳值型別一致

3.3 案例代碼實作

  • 修改SQL映射檔案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">
    <!--
        namespace:命名空間
    -->
    <mapper namespace="priv.dandelion.mapper.UserMapper">
        <select id="selectAll" resultType="priv.dandelion.entity.User">
            select * from tb_user;
        </select>
    </mapper>
    
  • 創建對應的Mapper介面UserMapper.interface

    public interface UserMapper {
        List<User> selectAll();
    }
    
  • 修改mybatis核心組態檔中加載SQL映射的<mapper></mapper>的路徑

    <mappers>
        <mapper resource="priv/dandelion/mapper/UserMapper.xml"/>
    </mappers>
    
  • 測驗代碼

    public static void main(String[] args) throws IOException {
        // 加載mybatis的核心組態檔,獲取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 獲取Session物件,執行SQL陳述句
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 執行SQL,處理結果
        // 獲取UserMapper介面的代理物件
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();
        System.out.println(users);
        // 釋放資源
        sqlSession.close();
    }
    
  • 改進

    如果Mapper介面名稱和SQL映射檔案名稱相同,并在同一目錄下,則可以使用包掃描的方式簡化SQL映射檔案的加載,簡化mybatis核心組態檔

    <mappers>
        <!--加載sql映射檔案-->
        <!-- <mapper resource="priv/dandelion/mapper/UserMapper.xml"/>-->
        <!--Mapper代理方式-->
        <package name="priv.dandelion.mapper"/>
    </mappers>
    

4、核心組態檔

4.1 多環境配置

在核心組態檔的 environments 標簽中其實是可以配置多個 environment ,使用 id 給每段環境起名,在 environments 中使用 default='環境id' 來指定使用哪兒段配置,我們一般就配置一個 environment 即可

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

    <typeAliases>
        <package name="priv.dandelion.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <!-- 采用JDBC的事務管理方式 -->
            <transactionManager type="JDBC"/>
            <!-- 資料庫連接資訊 -->
            <dataSource type="POOLED">
                <property name="driver" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/com.mysql.jdbc.Driver"/>
                <!-- JDBC連接資料庫,SSL,Unicode字符集,UTF-8編碼 -->
                <property name="url" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/jdbc:mysql:///mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/root"/>
                <property name="password" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/123456"/>
            </dataSource>
        </environment>

        <environment id="test">
            <transactionManager type="JDBC"/>
            <!-- 資料庫連接資訊 -->
            <dataSource type="POOLED">
                <property name="driver" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/com.mysql.jdbc.Driver"/>
                <property name="url" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/root"/>
                <property name="password" value="https://www.cnblogs.com/dandelion-000-blog/archive/2022/08/29/123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 加載SQL映射檔案 -->
    <mappers>
        <!-- <mapper resource="priv/dandelion/mapper/UserMapper.xml"/>-->
        <package name="priv.dandelion.mapper"/>
    </mappers>
</configuration>

4.2 型別別名

映射組態檔中的resultType屬性需要配置資料封裝的型別(類的全限定名),繁瑣

Mybatis 提供了 型別別名(typeAliases) 可以簡化這部分的書寫

<configuration>
    <!-- name屬性未物體類所在的包 -->
    <typeAliases>
        <package name="priv.dandelion.entity"/>
    </typeAliases>
</configuration>
<mapper namespace="priv.dandelion.mapper.UserMapper">
    <!-- resultType的值不區分大小寫 -->
    <select id="selectAll" resultType="user">
        select * from tb_user;
    </select>
</mapper>

5、組態檔實作CRUD

5.1 環境準備

  • 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;
    
  • 物體類

    public class Brand {
        
        private Integer id;
        private String brand_name;
        private String company_name;
        private Integer ordered;
        private String description;
        private Integer status;
    
        public Brand() {
        }
    
        public Brand(
                Integer id,
                String brand_name,
                String company_name,
                Integer ordered,
                String description,
                Integer status
        ) {
            this.id = id;
            this.brand_name = brand_name;
            this.company_name = company_name;
            this.ordered = ordered;
            this.description = description;
            this.status = status;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getBrand_name() {
            return brand_name;
        }
    
        public void setBrand_name(String brand_name) {
            this.brand_name = brand_name;
        }
    
        public String getCompany_name() {
            return company_name;
        }
    
        public void setCompany_name(String company_name) {
            this.company_name = company_name;
        }
    
        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;
        }
    
        @Override
        public String toString() {
            return "Brand{" +
                    "id=" + id +
                    ", brand_name='" + brand_name + '\'' +
                    ", company_name='" + company_name + '\'' +
                    ", ordered=" + ordered +
                    ", description='" + description + '\'' +
                    ", status=" + status +
                    '}';
        }
    }
    
  • 安裝插件MyBatisX

  • 步驟

    1. 撰寫介面方法Mapper介面
      • 引數
      • 回傳值
    2. 在SQL映射檔案中撰寫SQL陳述句
      • MyBatisX插件自動補全
      • 撰寫SQL
      • 若資料庫欄位名和物體類欄位名不同,則需要解決該問題(見 5.2 SQL映射檔案)
    3. 撰寫執行測驗
      • 獲取SqlSessionFactory
      • 獲取sqlSession物件
      • 獲取mapper介面的代理物件
      • 執行方法
      • 釋放資源

5.2 查詢所有資料

本節要點:

  1. 測驗類的撰寫方式
  2. 解決資料庫欄位和物體類欄位名不同的問題
  • 撰寫介面方法

    public interface BrandMapper {
        public List<Brand> selectAll();
    }
    
  • 撰寫SQL映射檔案

    <?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">
    <!--
        namespace:命名空間
    -->
    <mapper namespace="priv.dandelion.mapper.BrandMapper">
    
    <!-- 起別名解決資料庫和物體類欄位名不同問題
        <sql id="brand_column">
            id, brand_name as brandName, company_name as companyName, ordered, description, status
        </sql>
    
        <select id="selectAll" resultType="priv.dandelion.entity.Brand">
            select * from tb_brand;
    
            select
                <include refid="brand_column"/>
            from tb_brand;
        </select>
     -->
    
        <!-- resultMap解決資料庫和物體類欄位不同問題 -->
        <resultMap id="brandResultMap" type="brand">
            <result column="brand_name" property="brandName" />
            <result column="company_name" property="companyName" />
        </resultMap>
    
        <!-- 不使用resultType, 使用resultMap -->
        <select id="selectAll" resultMap="brandResultMap">
            select *
            from tb_brand;
        </select>
    
    </mapper>
    
  • 撰寫測驗方法

    @Test
    public void testSelectAll() throws IOException {
        // 獲取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
        // 獲取sqlSession物件
        SqlSession sqlSession = sqlSessionFactory.openSession();
    
        // 獲取mapper介面的代理物件
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
        // 執行方法
        List<Brand> brands = brandMapper.selectAll();
        System.out.println(brands);
    
        // 釋放資源
        sqlSession.close();
    }
    

5.3 查詢

本節要點:

  1. MyBatis的SQL映射檔案中,SQL陳述句如何接收對應引數
  • 使用占位符進行引數傳遞

    • 占位符名稱和引數保持一致

    • 占位符

      • #{占位符名}:會替換為?防止SQL注入,一般用于替換欄位值
      • ${占位符名}:存在SQL注入問題,一般用于執行動態SQL陳述句,如表名列名不固定的情況(見)
  • 撰寫介面方法

    void update(Brand brand);
    
  • SQL映射檔案查詢代碼標簽

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName" />
        <result column="company_name" property="companyName" />
    </resultMap>
    <select id="selectById" resultMap="brandResultMap">
        select *
        from tb_brand where id = #{id};
    </select>
    
  • 測驗方法

    @Test
        public void testSelectByCondition() throws IOException {
            // 接收引數
            int status = 1;
            String companyName = "華為";
            String brandName = "華為";
    
            // 獲取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = 
                new SqlSessionFactoryBuilder().build(inputStream);
    
            // 獲取sqlSession物件
            SqlSession sqlSession = sqlSessionFactory.openSession();
    
            // 獲取mapper介面的代理物件
            BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
            // 執行方法
            companyName = "%" + companyName + "%";
            brandName = "%" + brandName + "%";
            List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
            System.out.println(brands);
    
            // 釋放資源
            sqlSession.close();
        }
    

5.4 多條件查詢

本節要點:

  1. 多條件查詢:如果有多個引數,需要使用@Paran("SQL引數占位符名稱")注解
  2. 多條件的動態條件查詢:物件屬性名稱要和引數占位符名稱一致
    (詳見5-2解決資料庫欄位和物體類欄位名不同的問題)
  3. 單條件的動態條件查詢:保證key要和引數占位符名稱一致
  • 多條件查詢

    • SQL映射檔案

      <!-- resultMap解決資料庫和物體類欄位不同問題 -->
      <resultMap id="brandResultMap" type="brand">
          <result column="brand_name" property="brandName"/>
          <result column="company_name" property="companyName"/>
      </resultMap>
      
      <!-- 條件查詢 -->
      <select id="selectByCondition" resultMap="brandResultMap">
          select *
          from tb_brand
          where status = #{status}
          and company_name like #{companyName}
          and brand_name like #{brandName}
      </select>
      
    • 散裝引數

      • 介面

        // 散裝引數
        List<Brand> selectByCondition(
            @Param("status")int status, 
            @Param("companyName")String companyName, 
            @Param("brandName")String brandName
        );
        
      • 測驗方法

        @Test
            public void testSelectByCondition() throws IOException {
                // 接收引數
                int status = 1;
                String companyName = "華為";
                String brandName = "華為";
        
                // 獲取SqlSessionFactory
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                SqlSessionFactory sqlSessionFactory =
                    new SqlSessionFactoryBuilder().build(inputStream);
        
                // 獲取sqlSession物件
                SqlSession sqlSession = sqlSessionFactory.openSession();
        
                // 獲取mapper介面的代理物件
                BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        
                // 執行方法
                companyName = "%" + companyName + "%";
                brandName = "%" + brandName + "%";
                List<Brand> brands = brandMapper.selectByCondition(
                    status, companyName, brandName);
                System.out.println(brands);
        
                // 釋放資源
                sqlSession.close();
            }
        
    • 物件引數

      • 介面

        // 物件引數
        List<Brand> selectByCondition(Brand brand);
        
      • 測驗方法

        // 細節不表,僅展示執行方法
        // 執行方法
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName("%" + companyName + "%");
        brand.setBrandName("%" + brandName + "%");
        List<Brand> brands = brandMapper.selectByCondition(brand);
        System.out.println(brands);
        
    • map集合引數

      • 介面

        // 集合引數
        List<Brand> selectByCondition(Map map);
        
      • 測驗方法

        // 細節不表,僅展示執行方法
        // 執行方法
        Map map = new HashMap();
        map.put("status", status);
        map.put("companyName", "%" + companyName + "%");
        map.put("brandName", "%" + brandName + "%");
        List<Brand> brands = brandMapper.selectByCondition(map);
        System.out.println(brands);
        
  • 多條件動態條件查詢

    優化條件查詢,如頁面上表單存在多個條件選項,但實際填寫表單僅使用部分條件篩選的情況

    • SQL映射檔案

      <!-- resultMap解決資料庫和物體類欄位不同問題 -->
      <resultMap id="brandResultMap" type="brand">
          <result column="brand_name" property="brandName"/>
          <result column="company_name" property="companyName"/>
      </resultMap>
      
      <!-- 動態條件查詢 -->
      <select id="selectByCondition" resultMap="brandResultMap">
          select *
          from tb_brand
          <where>
              <if test="status != null">
                  status = #{status}
              </if>
              <if test="companyName != null">
                  and company_name like #{companyName}
              </if>
              <if test="brandName != null">
                  and brand_name like #{brandName}
              </if>
          </where>
      </select>
      

      注:

      1. if標簽的test屬性中可以包含邏輯或等邏輯判斷,使用andor進行連接

      2. 若條件SQL中同時包含AND等連接符

        • 對所有的條件前都加AND,并在WHERE后加任意真判斷,即WHERE 1=1 AND ... AND ...
        • 加入<if></if>判斷標簽造輪子,自行決定添加AND的條件
        • 使用<where></where>標簽替換原SQL中的WHERE關鍵字,MyBatis將自動進行語法修正,如示例所示
  • 單條件的動態條件查詢

    優化條件查詢:如表單中存在多個條件篩選,但僅有其中一個生效的情況

    • 使用標簽
      • choose標簽類似于Java中的switch
      • when標簽類似于Java中的case
      • otherwise標簽類似于Java中的default
    • SQL映射檔案

      <!-- resultMap解決資料庫和物體類欄位不同問題 -->
      <resultMap id="brandResultMap" type="brand">
          <result column="brand_name" property="brandName"/>
          <result column="company_name" property="companyName"/>
      </resultMap>
      
      <!-- 單條件動態查詢 -->
      <select id="selectByConditionSingle" resultMap="brandResultMap">
          select *
          from tb_brand
          <where>
              <choose>
                  <when test="status != null">
                      status = #{status}
                  </when>
                  <when test="companyName != null and companyName != ''">
                      company_name like #{companyName}
                  </when>
                  <when test="brandName != null and brandName != ''">
                      brand_name like #{brandName}
                  </when>
              </choose>
          </where>
      </select>
      

5.6 添加資料與MyBatis事務

  • 添加

    • 介面

      // 添加
      void add(Brand brand);
      
    • SQL映射檔案

      <insert id="add">
          insert into tb_brand (brand_name, company_name, ordered, description, status)
          values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
      </insert>
      
    • 測驗方法

      @Test
      public void testAdd() throws IOException {
          // 接收引數
          int status = 1;
          String companyName = "aaa";
          String brandName = "xxx";
          String description = "這是一段介紹";
          int ordered = 100;
      
          // 獲取SqlSessionFactory
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
          SqlSessionFactory sqlSessionFactory = 
              new SqlSessionFactoryBuilder().build(inputStream);
      
          // 獲取sqlSession物件
          // SqlSession sqlSession = sqlSessionFactory.openSession();
          SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
          // 獲取mapper介面的代理物件
          BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
      
          // 執行方法
          Brand brand = new Brand();
          brand.setStatus(1);
          brand.setBrandName(brandName);
          brand.setCompanyName(companyName);
          brand.setDescription(description);
          brand.setOrdered(ordered);
          brandMapper.add(brand);
          System.out.println("添加成功");
      
          // 提交事務
          // sqlSession.commit();
      
          // 釋放資源
          sqlSession.close();
      }
      
  • Mybatis事務

    MyBatis默認手動事務,執行添加等操作時會自動回滾

    • MyBayis事務處理的方法

      // 方法一:在獲取sqlSession物件時設定引數,開啟自動事務
      SqlSession sqlSession = sqlSessionFactory.openSession(true);
      sqlSession.close();
      // 方法二:手動提交事務
      SqlSession sqlSession = sqlSessionFactory.openSession();
      sqlSession.commit();
      sqlSession.close();
      
  • 添加 - 主鍵回傳

    傳入物體類物件進行資料添加,在資料添加完成后,會將id資訊寫回該物體類物件

    • SQL映射檔案

      <insert id="add" useGeneratedKeys="true" keyProperty="id">
          insert into tb_brand (brand_name, company_name, ordered, description, status)
          values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
      </insert>
      
    • 獲取寫回資訊

      Integer id = brand.getId();
      

5.7 修改

  • 修改整條資料

    • 介面

      // 修改,可使用int回傳值,回傳受影響行數
      void update(Brand brand);
      
    • SQL映射檔案

      <update id="update">
          update tb_brand
          set brand_name = #{brandName},
          set company_name = #{companyName},
          set ordered = #{ordered},
          set description = #{description},
          set status = #{status}
          where id = #{id};
      </update>
      
  • 修改部分欄位

    優化上述代碼應對僅修改部分屬性導致其他屬性資料丟失問題

    使用<set></set>標簽替換set關鍵字串列,區別于<where></where>標簽,注意語法

    • SQL映射檔案

      <update id="update">
          update tb_brand
          <set>
              <if test="brandName != null and brandName != ''">
                  brand_name = #{brandName},
              </if>
              <if test="companyName != null and companyName != ''">
                  company_name = #{companyName},
              </if>
              <if test="ordered != null">
                  ordered = #{ordered},
              </if>
              <if test="description != null and description != ''">
                  description = #{description},
              </if>
              <if test="status != null">
                  status = #{status},
              </if>
          </set>
          where id = #{id};
      </update>
      
    • 測驗代碼

      @Test
      public void testUpdate() throws IOException {
          // 接收引數
          int id = 5;
          int status = 0;
          String companyName = "AAA";
          String brandName = "XXX";
          int ordered = 300;
      
          // 獲取SqlSessionFactory
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
          SqlSessionFactory sqlSessionFactory = 
              new SqlSessionFactoryBuilder().build(inputStream);
      
          // 獲取sqlSession物件
          SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
          // 獲取mapper介面的代理物件
          BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
      
          // 執行方法
          Brand brand = new Brand();
          brand.setId(id);
          brand.setStatus(status);
          brand.setBrandName(brandName);
          brand.setCompanyName(companyName);
          brand.setOrdered(ordered);
          brandMapper.update(brand);
          System.out.println("修改成功");
      
          // 釋放資源
          sqlSession.close();
      }
      

5.8 洗掉資料

  • 洗掉一條資料

    • 介面

      // 洗掉一條資料
      void deleteById(int id);
      
    • SQL映射檔案

      <delete id="deleteById">
          delete
          from tb_brand
          where id = #{id};
      </delete>
      
    • 測驗

      @Test
      public void testDeleteById() throws IOException {
          // 接收引數
          int id = 5;
      
          // 獲取SqlSessionFactory
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
          SqlSessionFactory sqlSessionFactory = 
              new SqlSessionFactoryBuilder().build(inputStream);
      
          // 獲取sqlSession物件
          SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
          // 獲取mapper介面的代理物件
          BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
      
          // 執行方法
          brandMapper.deleteById(id);
          System.out.println("洗掉成功");
      
          // 釋放資源
          sqlSession.close();
      }
      
  • 批量洗掉資料

    用于解決洗掉時傳入引數為陣列的情況

    • 使用<foreach></foreach>標簽代替SQL陳述句中的id in (?, ?, ..., ?)
      • collection屬性為MyBatis封裝后陣列對應的key,封裝后屬性值應為array(見注釋)
        • MyBatis默認會將陣列引數封裝為Map集合,其keyarray,即 array = ids
        • 可在介面中對引數陣列使用@Param注解,將封裝后的key手動命名,則可在映射檔案中使用
      • separator屬性為分隔符
      • openclose屬性分別為在<foreach></foreach>前后拼接字符,主要用于代碼規范,示例中未展示
    • 介面

      // 洗掉多個資料
      void deleteByIds(@Param("ids")int[] ids);
      
    • SQL映射檔案

      <delete id="deleteByIds">
          delete
          from tb_brand
          where id
          in (
          <!-- <foreach collection="array" item="id"> -->
          <foreach collection="ids" item="id" separator=",">
              #{id}
          </foreach>
          );
      </delete>
      
    • 測驗

      @Test
      public void testDeleteByIds() throws IOException {
          // 接收引數
          int[] ids = {6, 7};
      
          // 獲取SqlSessionFactory
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
          SqlSessionFactory sqlSessionFactory = 
              new SqlSessionFactoryBuilder().build(inputStream);
      
          // 獲取sqlSession物件
          SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
          // 獲取mapper介面的代理物件
          BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
      
          // 執行方法
          brandMapper.deleteByIds(ids);
          System.out.println("洗掉成功");
      
          // 釋放資源
          sqlSession.close();
      }
      

5.9 MyBatis引數傳遞

  • 概述

  • 多個引數

    設有如下代碼:

    User select(@Param("username") String username,@Param("password") String password);
    

    MyBatis會將散裝的多個引數封裝為Map集合

    • 若不使用@Param注解,則會使用以下命名規則:

      map.put("arg0",引數值1);
      map.put("arg1",引數值2);
      map.put("param1",引數值1);
      map.put("param2",引數值2);
      

      即Map集合中的引數的key分別為arg0, arg1, param1, param2

    • 使用@Param注解會將Map集合中的引數的arg替換為指定內容,增強其可讀性

  • 單個引數

    • POJO型別:直接使用,要求屬性名和引數占位符名稱一致(見 5.2 SQL映射檔案)

    • Map集合型別:直接使用,要求key和引數占位符名稱一致(見 5.2 SQL映射檔案)

    • Collection集合型別:封裝Map集合,可以使用@Param注解替換Map集合中默認arg鍵名

      map.put("arg0",collection集合);
      map.put("collection",collection集合;
      
    • List集合型別:封裝為Map集合,可以使用@Param注解,替換Map集合中默認的arg鍵名

      map.put("arg0",list集合);
      map.put("collection",list集合);
      map.put("list",list集合);
      
    • Array型別:封裝為Map集合,可以使用@Param注解,替換Map集合中默認的arg鍵名

      map.put("arg0",陣列);
      map.put("array",陣列);
      
    • 其他型別:直接使用,與引數占位符無關,但盡量見名知意

6、通過注解實作CRUD

  • 概述

    • 用于簡化開發,可以對簡單的查詢使用注解進行操作,以替換xml中的statement
    • 對于復雜的查詢,仍然建議使用xml組態檔,否則代碼會十分混亂
  • 使用方法

    • 注解(部分)

      • 查詢 :@Select
      • 添加 :@Insert
      • 修改 :@Update
      • 洗掉 :@Delete
    • 示例

      • 使用注解簡化查詢

        • 原介面

          Brand selectById(int id);
          
        • 原SQL映射檔案

          <!-- resultMap解決資料庫和物體類欄位不同問題 -->
          <resultMap id="brandResultMap" type="brand">
              <result column="brand_name" property="brandName"/>
              <result column="company_name" property="companyName"/>
          </resultMap>
          
          <select id="selectById" resultMap="brandResultMap">
              select *
              from tb_brand
              where id = #{id};
          </select>
          
        • 使用注解進行開發

          • 介面

            @ResultMap("brandResultMap")		// 解決資料庫和物體類欄位名稱不同
            @Select("select * from tb_brand where id = #{id}")	// 查詢陳述句
            Brand selectById(int id);
            
          • SQL映射檔案:不再需要原先的statement

            <!-- resultMap解決資料庫和物體類欄位不同問題 -->
            <resultMap id="brandResultMap" type="brand">
                <result column="brand_name" property="brandName"/>
                <result column="company_name" property="companyName"/>
            </resultMap>
            
            <!--
            <select id="selectById" resultMap="brandResultMap">
                select *
                from tb_brand
                where id = #{id};
            </select>
            -->
            

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503077.html

標籤:其他

上一篇:《Python編程從入門到實踐》第2版 PDF高清版電子書

下一篇:自動下載視頻、彈幕、評論軟體【python制作】

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more