
🧸安清h:个人主页
🎥个人专栏:【计算机网络】
🚦作者简介:一个有趣爱睡觉的intp,期待和更多人分享自己所学知识的真诚大学生。

文章目录
🎯一.动态SQL简单介绍
🚦动态SQL的基本概念
🎯二.条件查询操作
🚦数据库准备
🚦POJO类准备
🚦创建映射文件(元素)
🚦修改核心配置文件
🚦创建MybatisUtil工具类
🚦创建接口类
🚦修改测试类
✨,,元素
✨更新操作
✨复杂查询操作
🍔元素简单介绍
🍔元素迭代List
🍔元素迭代数组
🍔元素迭代Map
🎯总结
🎯一.动态SQL简单介绍
动态SQL是MyBatis框架中一个非常强大的特性,它允许开发者在构建SQL语句时根据条件动态地生成不同的SQL片段。这样做的好处是可以避免硬编码查询逻辑,简化数据库查询的复杂度,同时提高代码的可读性和维护性。
🚦动态SQL的基本概念
动态SQL并不是一个新的概念,它指的是在运行时根据条件构建SQL语句,而不是使用静态的SQL语句。MyBatis通过一系列的动态SQL标签来实现这一功能,这些标签包括:
<if>:根据条件动态拼接SQL。
<choose>、<when>、<otherwise>:类似于Java中的switch-case语句。
<trim>、<where>、<set>:用于处理SQL语句的不同部分,如自动添加WHERE,并去除多余的AND。
<foreach>:用于处理集合,生成IN查询。
🎯二.条件查询操作
🚦数据库准备
在数据库mybatis下,创建一个customer表,并向其中插入几条数据,代码如下:
create table customer(
    id int(32) primary key auto_increment,
    username varchar(50),
    jobs varchar(50),
    phone varchar(16)
);
insert into customer values ('1','joy','teacher','122222222');
insert into customer values ('2','jack','teacher','133333333');
insert into customer values ('3','tom','worker','1267567567');🚦POJO类准备
一般放在pojo包里,这里我直接在java包中建立了,类中声明id,username,jobs,phone属性,以及属性相对应get/set方法。
public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;
    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 getJobs() {
        return jobs;
    }
    public void setJobs(String jobs) {
        this.jobs = jobs;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}
🚦创建映射文件(<if>元素)
if元素中的test属性多用于条件判断语句中,用于判断真假,在此处,我们对用户姓名和工作都做了非空判断,如果传入的查询条件非空就进行动态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">
<mapper namespace="CustomerMapper">
    <select id="QueryByNameAndJobs" parameterType="Customer" resultType="Customer">
        select * from customer
            where 1=1
        <if test="username!=null and username!=''">
           and username like concat('%',#{username},'%')
        </if>
        <if test="jobs!=null and jobs!=''">
            and jobs=#{jobs}
        </if>
    </select>
</mapper>🚦修改核心配置文件
在核心配置文件mybatis-config.xml中引入CustomerMapper.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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="CustomerMapper.xml"/>
    </mappers>
</configuration>🚦创建MybatisUtil工具类
这段代码的目的是为了封装MyBatis的初始化过程,并提供一个全局访问点来获取SqlSession,使得在应用的其他部分可以很方便地使用MyBatis进行数据库操作,而不需要关心SqlSessionFactory的创建和配置细节。这样做可以减少代码重复,提高代码的可维护性。
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory=null;
    
    static {
        try {
            Reader reader= Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}🚦创建接口类
public interface CustomerMapper {
    List<Customer> QueryByNameAndJobs(Customer customer);
}🚦修改测试类
在测试类MybatisTest中,编写测试方法testQuery,该方法用于通过姓名和工作查询客户信息。
public class MybatisTest {
    @Test
    public void testQuery(){
        SqlSession sqlSession=MybatisUtil.getSession();
        CustomerMapper customerMapper=sqlSession.getMapper(CustomerMapper.class);
        Customer customer=new Customer();
        customer.setUsername("jack");
        customer.setJobs("teacher");
        List<Customer> list=customerMapper.QueryByNameAndJobs(customer);
        for(Customer c:list){
            System.out.println(c);
        }
        sqlSession.close();
    }
}✨<choose>,<when>,<otherwise>元素
在MyBatis的动态SQL中,
<choose>,<when>,<otherwise>元素组合用于条件分支选择,类似于Java中的if-else或switch语句。这些元素允许在SQL语句中根据不同的条件执行不同的SQL片段。以下是这些元素的基本用法:
<choose>元素表示一个条件选择块的开始,它本身不生成任何SQL语句。
<when>元素表示一个条件分支,它内部包含一个test属性,该属性用于指定条件表达式。如果test属性中的表达式计算为true,则该分支内的SQL会被包含在最终的SQL语句中。
<otherwise>元素表示在所有<when>条件都不满足时执行的分支。它类似于switch语句中的default分支。
(1)在映射文件CustomerMapper.xml中,添加使用 <choose>,<when>,<otherwise>实现以下场景:
- 在客户名称不为空时,只根据客户名称查找。
- 客户名称为空,客户职业不为空时,只根据客户职业查找。
- 客户名称和客户职业都为空时,查询出所有电话不为空的客户信息。
<?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="CustomerMapper">
    <select id="findByWhere" parameterType="Customer" resultType="Customer">
        select * from customer where 1=1
        <choose>
            <when test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </when>
            <when test="jobs!=null and jobs!=''">
                and jobs=#{jobs}
            </when>
            <otherwise>
                and phone is not null
            </otherwise>
        </choose>
    </select>
</mapper>上述使用<choose>元素进行SQL拼接,当第一个<when>元素中的条件为真时,只动态组装第一个<when>元素内的SQL片段并执行,否则就继续向下判断第二个<when>元素中的条件是否为真,以此类推,直到某个<when>元素中的条件为真,结束判断。当前面所有的<when>元素中的条件都不为真时,则动态组装<otherwise>元素内的SQL片段并执行。
(2)在测试类MybatisTest中,编写测试方法findByWhere(),具体代码如下:
public class MybatisTest {
    @Test
    public void findByWhere(){
        SqlSession sqlSession=MybatisUtil.getSession();
        CustomerMapper customerMapper=sqlSession.getMapper(CustomerMapper.class);
        Customer customer=new Customer();
        customer.setUsername("jack");
        customer.setJobs("teacher");
        List<Customer> list=customerMapper.findByWhere(customer);
        for(Customer c:list){
            System.out.println(c);
        }
        sqlSession.close();
    }
}不同的查询结果如下:
1.客户姓名不为空时

2.客户姓名为空,客户职业不为空时

3.客户姓名和客户职业都为空时

✨更新操作
在MyBatis中,<set>标签用于构建动态SQL语句中的UPDATE操作,它允许根据条件动态地更新表中的列。<set>标签会自动地为你插入的每个列添加逗号分隔,并且会忽略空格,使得构建动态更新语句更加方便。
<set>标签通常与<if>标签结合使用,以便在运行时根据条件动态地构建更新的列和值。以下是一个基本的示例:
(1)在映射文件CustomerMapper.xml中,使用<set>元素执行更新操作的动态SQL:
<update id="updateCustomerBySet" parameterType="Customer">
        update customer
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="jobs!=null and jobs!=''">
                jobs=#{jobs}
            </if>
            <if test="phone!=null and phone!=''">
                phone=#{phone}
            </if>
        </set>
        where id=#{id}
    </update>(2)在CustomerMapper接口中添加如下操作:
public interface CustomerMapper {
    int updateCustomerBySet(Customer customer);
}(3)在测试类MybatisTest中编写测试方法testUpdate(),具体实现代码如下:
@Test
    public void testUpdate(){
        SqlSession sqlSession=MybatisUtil.getSession();
        CustomerMapper customerMapper=sqlSession.getMapper(CustomerMapper.class);
        Customer customer=new Customer();
        customer.setId(3);
        customer.setPhone("123456789");
        int rows=customerMapper.updateCustomerBySet(customer);
        if(rows>0){
            System.out.println("您修改成功了"+rows+"条数据");
        }else{
            System.out.println("您修改失败了!");
        }
        sqlSession.commit();
        sqlSession.close();
    }(4)修改成功后就可以看到:

在表中的数据如下图:
 
✨复杂查询操作
🍔<foreach>元素简单介绍
在MyBatis中,
<foreach>标签用于遍历集合,常用于构建IN条件子句或批量操作(如批量插入、更新、删除)。<foreach>标签可以处理集合或数组类型的参数,为每个元素生成SQL片段,并将这些片段组合起来。
属性 描述 collection
指定要遍历的集合或数组
item
指定集合中每个元素的别名,可以在遍历块内部使用
index
指定集合中每个元素的索引或键的别名,可以在遍历块内部使用
open
指定遍历输出的开始符号
close
指定遍历输出的结束符号
separator
指定遍历元素之间的分隔符
nullable
指定是否允许collection为空值
🍔<foreach>元素迭代List
(1)在映射文件CustomerMapper.xml中,添加使用<foreach>元素迭代List执行批量查询操作,具体代码如下:
<select id="findByArray" resultType="Customer">
        select * from Customer where id in
        <foreach item="id" collection="list" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>(2)在测试类MybatisTest中编写测试方法testforeach(),具体实现代码如下:
    @Test
    public void testforeach(){
        SqlSession sqlSession=MybatisUtil.getSession();
        Customer customer=new Customer();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(2);
        ids.add(3);
       List<Customer> list=sqlSession.selectList("CustomerMapper.findByArray",ids);
        for(Customer c:list){
            System.out.println(c);
        }
        sqlSession.close();
    }(3)在接口CustomerMapper 中添加以下代码:
List<Customer> findByArray(String customerMapper, List<Integer> ids);(4)查询结果如下图:

🍔<foreach>元素迭代数组
(1)在映射文件CustomerMapper.xml中,添加使用<foreach>元素迭代数组执行批量查询操作,具体代码如下:
    <select id="findByList" resultType="Customer">
        select * from Customer where id in
        <foreach item="id" collection="list" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>(2)在测试类MybatisTest中编写测试方法testforeach(),具体实现代码如下:
    @Test
    public void testforeach(){
        SqlSession sqlSession=MybatisUtil.getSession();
        Customer customer=new Customer();
        Integer[] ids={1,2};
        List<Customer> list=sqlSession.selectList("CustomerMapper.findByList",ids);
        for(Customer c:list){
            System.out.println(c);
        }
        sqlSession.close();
    }🍔<foreach>元素迭代Map
由于Mybatis传入参数均为一个参数,如果传入参数为多个参数,例如,查询出性别为男性且职业为教师的所有客户信息,此时,需要把这些参数封装成一个Map集合进行处理。
(1)在映射文件CustomerMapper.xml中,添加使用<foreach>元素迭代Map执行批量查询操作,具体代码如下:
<select id="findByMap" parameterType="java.util.Map" resultType="Customer">
        select * from customer where jobs=#{jobs} and id in
        <foreach item="roleMap" index="index" collection="id" open="(" separator="," close=")">
            #{roleMap}
        </foreach>
    </select>(2)在测试类MybatisTest中编写测试方法testforeach(),具体实现代码如下:
    @Test
    public void testforeach(){
        SqlSession sqlSession=MybatisUtil.getSession();
        List<Integer> ids=new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("id",ids);
        map.put("jobs","teacher");
        List<Customer> list=sqlSession.selectList("CustomerMapper.findByMap",map);
        for(Customer c:list){
            System.out.println(c);
        }
        sqlSession.close();
    }
🎯总结
 以上就是今天要讲的内容了,主要在<if>,<choose>,<when>,<otherwise>,<foreach>方面做了重点的讲解,非常感谢您的阅读,如果这篇文章对您有帮助,那将是我的荣幸。我们下期再见啦🧸!









![学习docker第二弹------基本命令[帮助启动类命令、镜像命令、容器命令]](https://i-blog.csdnimg.cn/direct/4e8f154722fb46e09b46f9a0d9dc9faa.png)









