zoukankan      html  css  js  c++  java
  • 11.10Mybatis之动态SQL

    11.10Mybatis之动态SQL

    动态SQL的应用场景

    JDBC或者其他框架中的拼接SQL的场景。

    Mybatis动态SQL包含的元素

    元素作用备注
    if 判断语句 单条件分支判断
    choose(when、otherwise) 相当于 Java 中的 switch case 语句 多条件分支判断
    trimwhere 辅助元素 用于处理一些SQL拼装问题
    foreach 循环语句 在in语句等列举条件常用
    bind 辅助元素 拼接参数

    if标签

    判断条件,常与test属性连用:

    语法:

    <if test="判断条件">
    SQL语句
    </if>

    判断条件为true则会执行语句。

    可以多个判断,可以单个判断,可以和where子句一起使用。

    <?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.junkingboy.mapper.WebsiteMapper">
       <!-- 使用if判断标签进行条件判断 -->
       <select id="selectAllWebsite2" resultMap="myResult">
          SELECT id, name, url
          FROM javawebtest.website
          WHERE 1 = 1
       <if test="name != null">
          AND name = #{name};
       </if>

       <if test="url != null">
          AND url = #{url};
       </if>
       </select>
    </mapper>

    上诉语句的意义:

    • 可以按照网站名称(name)或者网址(url)进行模糊查询

    • 如果不传参则返回全部的网站信息

    choose...when...otherwise标签

    选择执行条件,类似Java当中的switch...case...default语句

    Mybatis框架中没有if...else标签

    语法:

    <choose>
    <when test="判断条件1">
      SQL语句1
       </when>
       <when test="判断条件2">
      SQL语句2
       </when>
       <when test="判断条件3">
      SQL语句3
       </when>
       <otherwise>
      SQL语句4
       </otherwise>
    </choose>

    说明:

    • when标签中的判断条件是否成立,如果有一个成立,则执行相应的 SQL语句,choose执行结束

    • 如果when 标签中的判断条件都不成立,执行otherwise中的SQL语句

    示例代码:

    需求:

    • 当网站名称不为空时,只用网站名称作为条件进行模糊查询;

    • 当网站名称为空,而网址不为空时,则用网址作为条件进行模糊查询;

    • 当网站名称和网址都为空时,则要求网站年龄不为空。

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
       <!-- 使用choose标签进行选择执行sql的操作(使用自定义resultMap) -->
       <select id="selectWebsite" parameterType="com.junkingboy.bean.Website" resultType="com.junkingboy.bean.Website">
          SELECT id, name, url, age, country
          FROM javawebtest.website
          WHERE 1 = 1
       <!-- 使用choose标签进行switch...case的操作 -->
       <choose>
           <when test="name != null and name != ''">
              AND name
              LIKE CONCAT('%', #{name}, '%')
           </when>
           <when test="url != null and url != ''">
              AND url
              LIKE CONCAT('%', #{url}, '%')
           </when>
           <otherwise>
              AND age is not null
           </otherwise>
       </choose>
       </select>
    </mapper>

    websiteMapper接口类:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
       /* 查询所有网站信息,传参为Website对象 */
       List<Website> selectWebsite(Website website);
    }

    测试类:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
       //创建表的实现类对象
       Website website = new Website();
       List<Website> websiteList;
       InputStream is = null;
       SqlSessionFactory ssf;
       SqlSession ss;
       Boolean openSwitch = null;
       Integer changeNum = 0;
       /*
       步骤:
       Io流读取配置文件
       使用SqlSessionFactory接口实现类加载配置文件
       使用SqlSession接口开启连接
       获取WebsiteMapper接口定义的方法
       执行接口当中的方法
        */

       /*获取读取配置文件的方法*/
       private Boolean readProperties() {
           try {
               is = Resources.getResourceAsStream("xml/mybatis-config.xml");
          }catch (Exception e) {
               /*结束方法*/
               System.out.println("找不到配置文件!");
               e.printStackTrace();
               return false;
          }
           return true;
      }
       
       @Override
       public List<Website> selectWebsite(Website website) {
           openSwitch = readProperties();
           try {
               if (openSwitch == true) {
                   ssf = new SqlSessionFactoryBuilder().build(is);
                   ss = ssf.openSession();
                   /*创建website对象*/
                   Website ws = new Website();
                   /*设置website属性*/
                   ws.setName("JunkingBoy");
                   /*调用websiteMapper接口中的方法*/
                   websiteList = ss.selectList("com.junkingboy.mapper.WebsiteMapper.selectWebsite", ws);
                   /*打印结果集*/
                   for (Website webs :
                           websiteList) {
                       System.out.println(webs);
                  }
              }
          }catch (Exception e) {
               e.printStackTrace();
          }
           return websiteList;
      }
    }

    where标签

    where标签的意义:

    • 上诉语句中存在一个条件where 1=1如果没有那么语句则是错误的为

      • SELECT id, name, url, age, country
        FROM website
        AND name
        LIKE CONCAT('%', #{name}, '%')

    where标签主要是简化SQL语句中的条件判断:

    <where>
    <if test="判断条件">
      AND/OR ...
       </if>
    </where>

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
    <!-- 使用where标签替代sql语句的where -->
    <select id="selectWebsite" resultType="com.junkingboy.bean.Website">
    SELECT id, name, url
    FROM javawebtest.website
    <where>
    <if test="name != null">
    AND name
    LIKE #{name}
    </if>

    <if test="url != null">
    AND url
    LIKE #{url}
    </if>
    </where>
    </select>
    </mapper>

    websiteMapper接口

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
    /* 使用where标签替代sql中的where */
    List<Website> selectWebsite1(Website website);
    }

    测试类:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
    //创建表的实现类对象
    Website website = new Website();
    List<Website> websiteList;
    InputStream is = null;
    SqlSessionFactory ssf;
    SqlSession ss;
    Boolean openSwitch = null;
    Integer changeNum = 0;
    WebsiteMapper wm = null;
    /*
    步骤:
    Io流读取配置文件
    使用SqlSessionFactory接口实现类加载配置文件
    使用SqlSession接口开启连接
    获取WebsiteMapper接口定义的方法
    执行接口当中的方法
    */

    /*获取读取配置文件的方法*/
    private Boolean readProperties() {
    try {
    is = Resources.getResourceAsStream("xml/mybatis-config.xml");
    }catch (Exception e) {
    /*结束方法*/
    System.out.println("找不到配置文件!");
    e.printStackTrace();
    return false;
    }
    return true;
    }

    @Override
    public List<Website> selectWebsite1(Website website) {
    openSwitch = readProperties();
    try {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    Website ws = new Website();
    /* 设置对象属性 */
    ws.setName("帅气俊");
    websiteList = ss.selectList("com.junkingboy.mapper.WebsiteMapper.selectWebsite1", ws);
    for (Website webs :
    websiteList) {
    System.out.println(webs);
    }
    }catch (Exception e) {
    e.printStackTrace();
    }
    if (websiteList == null) {
    System.out.println("方法执行成功,但结果为空!");
    }
    return websiteList;
    }
    }

    set标签

    概念:

    • update语句搭配使用,,动态更新列

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
    <!-- 使用set标签动态修改一个数据 -->
    <select id="selectWebsite" resultType="com.junkingboy.bean.Website">
    SELECT *
    FROM javawebtest.website
    <where>
    <if test="id != null and id != ''">
    id = #{id}
    </if>
    </where>
    </select>

    <update id="updateWebsite" parameterType="com.junkingboy.bean.Website">
    UPDATE javawebtest.website
    <set>
    <if test="name != null">
    name = #{name}
    </if>
    <if test="url != null">
    url = #{url}
    </if>
    </set>
    </update>
    </mapper>

    websiteMapper接口:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
    /* 使用set标签来动态修改信息 */
    List<Website> selectWebsite2(Website website);

    int updateWebsite(Website site);
    }

    测试类:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
    //创建表的实现类对象
    Website website = new Website();
    List<Website> websiteList;
    InputStream is = null;
    SqlSessionFactory ssf;
    SqlSession ss;
    Boolean openSwitch = null;
    Integer changeNum = 0;
    WebsiteMapper wm = null;
    /*
    步骤:
    Io流读取配置文件
    使用SqlSessionFactory接口实现类加载配置文件
    使用SqlSession接口开启连接
    获取WebsiteMapper接口定义的方法
    执行接口当中的方法
    */

    /* 获取读取配置文件的方法 */
    private Boolean readProperties() {
    try {
    is = Resources.getResourceAsStream("xml/mybatis-config.xml");
    }catch (Exception e) {
    /*结束方法*/
    System.out.println("找不到配置文件!");
    e.printStackTrace();
    return false;
    }
    return true;
    }

    /* 循环遍历打印结果方法 */
    public void printResult(List<Website> website) {
    for (Website site :
    website) {
    System.out.println(site);
    }
    }

    @Override
    public List<Website> selectWebsite2(Website website) {
    openSwitch = readProperties();
    try {
    if (openSwitch == true) {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    website = new Website();
    website.setId(1);
    website.setUrl("www.junkingboy.com");

    /* 执行语句 */
    websiteList = ss.getMapper(WebsiteMapper.class).selectWebsite2(website);
    }
    }catch (Exception e) {
    e.printStackTrace();
    }
    if (websiteList!=null) {
    /* 循环遍历打印结果 */
    printResult(websiteList);
    }else {
    System.out.println("结果集为空!");
    }
    return websiteList;
    }

    @Override
    public int updateWebsite(Website website) {
    openSwitch = readProperties();
    if (openSwitch == true) {
    if (website!=null){
    try {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    wm = ss.getMapper(WebsiteMapper.class);
    changeNum = wm.updateWebsite(website);
    }catch (Exception e) {
    e.printStackTrace();
    }
    }else {
    System.out.println("形参对象为空!");
    return 0;
    }
    }
    if (changeNum==0) {
    System.out.println("方法执行成功,无符合数据!");
    return 1;
    }
    return changeNum;
    }
    }

    foreach标签

    应用场景:

    • SQL语句中含有in条件,需要迭代条件集合来生成的情况

    • 用于循环语句:

    <foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")">
    参数值
    </foreach>

    标签属性说明:

    • item:集合中每一个元素进行迭代时的别名

    • index:指定一个名字,表示在迭代过程中每次迭代到的位置

    • open:表示该语句以什么开始(是 in 条件语句,所以是以(开始)

    • separator:表示每次迭代之间以什么符号作为分隔符()

    • close:表示该语句以什么结束

    关键标签:

    • collection:必选属性,在不同情况下属性的值不一样

      • 传入单参数且参数类型是一个List,值为list

      • 传入单参数且参数类型是一个array,值为array

      • 传入多参数(需要把参数封装成Map)key是参数名,属性值是传入的listarray对象在自己封装的Map中的key

    创建测试数据:

    insert into javawebtest.website(name, url, age, country)
    values
    ('junkingboy', 'http://www.junkingboy.com', 10, 'CN'),
    ('百度', 'https://www.Baidu.com', 12, 'CN'),
    ('淘宝', 'https://www.taobao.com', 18, 'CN'),
    ('Google', 'https://www.google.com', 23, 'US'),
    ('GitHub', 'https://github.com', 13, 'US');

    websiteMapper的相关文件:

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
    <!-- 使用foreach循环标签查询sql当中的in后面的内容 -->
    <select id="selectWebsite" parameterType="com.junkingboy.bean.Website" resultType="com.junkingboy.bean.Website">
    SELECT id, name, url, age, country
    FROM javawebtest.website
    WHERE age IN
    <foreach collection="list" item="age" index="index" open="(" separator="," close=")">
    #{age}
    </foreach>
    </select>
    </mapper>
    <!--
    foreach标签跟在in后面(注意每个标签的位置)
    -->

    websiteMapper接口:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
    /* 使用foreach标签进行in后面的内容判断 */
    List<Website> selectWebsite(List<Integer> ageList);
    }

    测试方法:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
    //创建表的实现类对象
    Website website = new Website();
    List<Website> websiteList;
    InputStream is = null;
    SqlSessionFactory ssf;
    SqlSession ss;
    Boolean openSwitch = null;
    Integer changeNum = 0;
    WebsiteMapper wm = null;
    /*
    步骤:
    Io流读取配置文件
    使用SqlSessionFactory接口实现类加载配置文件
    使用SqlSession接口开启连接
    获取WebsiteMapper接口定义的方法
    执行接口当中的方法
    */

    /* 获取读取配置文件的方法 */
    private Boolean readProperties() {
    try {
    is = Resources.getResourceAsStream("xml/mybatis-config.xml");
    }catch (Exception e) {
    /*结束方法*/
    System.out.println("找不到配置文件!");
    e.printStackTrace();
    return false;
    }
    return true;
    }

    /* 循环遍历打印结果方法 */
    public void printResult(List<Website> website) {
    for (Website site :
    website) {
    System.out.println(site);
    }
    }

    @Override
    public List<Website> selectWebsite(List<Integer> ageList) {
    if (ageList == null) {
    System.out.println("形参为空!");
    return null;
    }
    openSwitch = readProperties();
    try {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    wm = ss.getMapper(WebsiteMapper.class);
    websiteList = wm.selectWebsite(ageList);
    }catch (Exception e) {
    e.printStackTrace();
    }
    if (websiteList == null) {
    System.out.println("方法执行成功,内容为空!");
    }
    return websiteList;
    }

    public static void main(String[] args) {
    WebsiteMapperImpl wmi = new WebsiteMapperImpl();
    List<Integer> ageList = new ArrayList<Integer>();
    ageList.add(10);
    ageList.add(12);
    List<Website> websiteList = wmi.selectWebsite(ageList);
    wmi.printResult(websiteList);
    }
    }

    bind标签

    应用场景:

    • 因为不同数据库的拼接函数和字符串连接符号不一样,使用该标签是为了解决这个问题的产生的

    语法:

    <select id="selectWebsite" resultType="com.junkingboy.bean.Website">
    <bind name="pattern" value="'%'+_parameter+'%'" />
    SELECT id, name, url, age, country
    FROM website
    WHERE name LIKE #{pattern}
    </select>

    bind元素属性说明:

    • value:传入实体类的某个字段,进行字符串拼接等特殊处理

    • name:给对应参数取的别名

    上诉.xml文件会:

    • _parameter代表传递进来的参数,和通配符连接后赋值给参数pattern

    • select语句中使用的是pattern变量进行模糊查询

    • 可以传递多个参数

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
    <!-- 使用bind标签传递多个参数 -->
    <select id="selectWebsite" resultType="com.junkingboy.bean.Website">
    <bind name="pattern_name" value="'%' + name + '%'" />
    <bind name="pattern_url" value="'%' + url + '%'" />
    SELECT id, name, url, age, country
    FROM javawebtest.website
    WHERE name LIKE #{pattern_name}
    AND url LIKE #{pattern_url}
    </select>
    </mapper>

    websiteMapper接口:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
    /* 使用bind标签加多参数 */
    List<Website> selectWebsite3(Website website);
    }

    测试类:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
    //创建表的实现类对象
    Website website = new Website();
    List<Website> websiteList;
    InputStream is = null;
    SqlSessionFactory ssf;
    SqlSession ss;
    Boolean openSwitch = null;
    Integer changeNum = 0;
    WebsiteMapper wm = null;
    /*
    步骤:
    Io流读取配置文件
    使用SqlSessionFactory接口实现类加载配置文件
    使用SqlSession接口开启连接
    获取WebsiteMapper接口定义的方法
    执行接口当中的方法
    */

    /* 获取读取配置文件的方法 */
    private Boolean readProperties() {
    try {
    is = Resources.getResourceAsStream("xml/mybatis-config.xml");
    }catch (Exception e) {
    /*结束方法*/
    System.out.println("找不到配置文件!");
    e.printStackTrace();
    return false;
    }
    return true;
    }

    /* 循环遍历打印结果方法 */
    public void printResult(List<Website> website) {
    for (Website site :
    website) {
    System.out.println(site);
    }
    }

    @Override
    public List<Website> selectWebsite3(Website website) {
    if (website!=null){
    openSwitch = readProperties();
    if (openSwitch == true) {
    try {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    wm = ss.getMapper(WebsiteMapper.class);
    websiteList = wm.selectWebsite3(website);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
    }
    if (websiteList==null){
    System.out.println("方法执行成功,内容为空!");
    }
    return websiteList;
    }
    }

    trim标签

    作用:

    • 去除 SQL 语句中多余的 AND 关键字、逗号或者给 SQL 语句前拼接 where、set 等后缀

    语法格式:

    <trim prefix="前缀" suffix="后缀" prefixOverrides="忽略前缀字符" suffixOverrides="忽略后缀字符">
    SQL语句
    </trim>

    属性说明:

    属性描述
    prefix 给SQL语句拼接的前缀,为 trim 包含的内容加上前缀
    suffix 给SQL语句拼接的后缀,为 trim 包含的内容加上后缀
    prefixOverrides 去除 SQL 语句前面的关键字或字符,该关键字或者字符由 prefixOverrides 属性指定。
    suffixOverrides 去除 SQL 语句后面的关键字或者字符,该关键字或者字符由 suffixOverrides 属性指定。

    理解:

    • prefix属性和prefixOverride属性相当于是用prefix替换掉prefixOverride属性的内容

    • prefixOverride属性的内容必须在prefixOverride所属标签的包裹中

    websiteMapper.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.junkingboy.mapper.WebsiteMapper">
    <!-- 使用trim标签替代sql中的where子句 -->
    <select id="selectWebsite" resultType="com.junkingboy.bean.Website">
    SELECT id, name, url, age, country
    FROM javawebtest.website
    <trim prefix="where" prefixOverrides="and">
    <if test="name != null and name != ''">
    AND name
    LIKE CONCAT('%', #{name}, '%')
    </if>
    <if test="url != null">
    AND url
    LIKE CONCAT('%', #{url}, '%')
    </if>
    </trim>
    </select>
    </mapper>

    websiteMapper接口:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Student;
    import com.junkingboy.bean.User;
    import com.junkingboy.bean.Website;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.type.JdbcType;

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

    /**
    * @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
    * @data: 2021/11/2 16:35
    * @author: Lucifer
    */
    public interface WebsiteMapper {
    /* 使用trim标签代替sql中的where子句 */
    List<Website> selectWebsite4(Website website);
    }

    测试方法:

    package com.junkingboy.mapper;

    import com.junkingboy.bean.Website;
    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 java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;

    /**
    * @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
    * @data: 2021/11/5 17:18
    * @author: Lucifer
    */
    public class WebsiteMapperImpl<T> implements WebsiteMapper {
    //创建表的实现类对象
    Website website = new Website();
    List<Website> websiteList;
    InputStream is = null;
    SqlSessionFactory ssf;
    SqlSession ss;
    Boolean openSwitch = null;
    Integer changeNum = 0;
    WebsiteMapper wm = null;
    /*
    步骤:
    Io流读取配置文件
    使用SqlSessionFactory接口实现类加载配置文件
    使用SqlSession接口开启连接
    获取WebsiteMapper接口定义的方法
    执行接口当中的方法
    */

    /* 获取读取配置文件的方法 */
    private Boolean readProperties() {
    try {
    is = Resources.getResourceAsStream("xml/mybatis-config.xml");
    }catch (Exception e) {
    /*结束方法*/
    System.out.println("找不到配置文件!");
    e.printStackTrace();
    return false;
    }
    return true;
    }

    /* 循环遍历打印结果方法 */
    public void printResult(List<Website> website) {
    for (Website site :
    website) {
    System.out.println(site);
    }
    }

    @Override
    public List<Website> selectWebsite4(Website website) {
    if (website!=null) {
    openSwitch = readProperties();
    if (openSwitch == true) {
    try {
    ssf = new SqlSessionFactoryBuilder().build(is);
    ss = ssf.openSession();
    wm = ss.getMapper(WebsiteMapper.class);
    websiteList = wm.selectWebsite4(website);
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    if (websiteList == null) {
    System.out.println("方法执行成功,内容为空!");
    }
    return websiteList;
    }
    }

    章节小结

    Mybatis框架事实上是简化了JDBC对数据库的操作。通过一系列标签实现实际业务中需要对数据库操作的各种场景。

    • 熟悉记住各种标签以及搭配标签的属性。

    • 掌握各种标签的具体位置以及SQL的具体位置

    • 重点关注<trim>标签,因为他可以替换SQL语句当中的where子句

    It's a lonely road!!!
  • 相关阅读:
    poj 2516 Minimum Cost (最小费用流 )
    new start
    关于c语言中的声明和定义
    多态性与虚函数之对象切片
    C专家编程之typedef
    QGroupBox设置边框
    多态性与虚函数之继承中的virtual 晚捆绑
    使用Map
    遍历控件
    C专家编程之枚举
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15543472.html
Copyright © 2011-2022 走看看