后端数据库开发高级之通过在xml文件中映射实现动态SQL

简介: 后端数据库开发高级之通过在xml文件中映射实现动态SQL

if where标签

一个非常重要的功能

随着用户的输入或者是外部条件的变化而改变的SQL语句

我们称为SQL语句

只有传形参的有值 其他的属性都是null

所以并没有查询到数据

我们不难免会发现我们先前的

SQL的语句是固定死的

这样局限性太高

在xml映射文件中使用if标签可以实现动态SQL

SQL语句会根据传入参数的数量而变化

if标签用来做条件判断 这个条件要声明

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--复制引用-->
<mapper namespace="org.example.mybatis.mapper.UserMapper">
 
    <!--动态语句-->
    <select id="list" resultType="org.example.mybatis.pojo.User">
        select * from emp
        where
 
        <if test="name !=null">
            name like concat('%',#{name},'%')
        </if>
 
        <if test="gender !=null">
            and gender = #{gender}
        </if>
 
        <if test="begin !=null and end !=null ">
            and entrydate between #{begin} and #{end}
        </if>
 
        order by update_time desc
    </select>
 
</mapper>

将SQL语句进行判断后填充

where标签 可以去除多余的and 和 where

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--复制引用-->
<mapper namespace="org.example.mybatis.mapper.UserMapper">
 
    <!--动态语句-->
    <select id="list" resultType="org.example.mybatis.pojo.User">
        select * from emp
        <where>
 
            <if test="name !=null">
                name like concat('%',#{name},'%')
            </if>
 
            <if test="gender !=null">
                and gender = #{gender}
            </if>
 
            <if test="begin !=null and end !=null ">
                and entrydate between #{begin} and #{end}
            </if>
 
        </where>
        
        order by update_time desc
    </select>
 
</mapper>

if 案例

更新三个字段

首先赋值指定内容的字段

接着删掉不需要修改的字段

启动更新

数据库表中的数据完成了更新

但是其余字段是null

根据id去更新时 我们写是写死的 每一次都要传递更新

传递就去更新字段 不传递字段值就是null

这样子的更新并不灵活 我们要将员工信息更细改为动态更新

动态更新员工 如果传递时有数值 就更新 没有传递值 就还是默认数值

在XML文件里映射并书写动态SQL语句

指定id 就

是映射的方法名 即SQL语句的标签 生成的update标签是根据书写的方法名自动识别的

动态映射

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--复制引用-->
<mapper namespace="org.example.mybatis.mapper.UserMapper">
 
    <update id="update">
        <!--动态更新SQL-->
        update emp
        set
        <if test="username !=null ">username=#{username},</if>
        <if test="password !=null ">password=#{password},</if>
        <if test="name !=null ">name=#{name},</if>
        <if test="gender !=null ">gender=#{gender},</if>
        <if test="image !=null ">image=#{image},</if>
        <if test="job !=null ">job=#{job},</if>
        <if test="deptID !=null ">dept_id=#{deptID},</if>
        <if test="entryDate !=null ">entrydate=#{entryDate},</if>
        <if test="creatTime !=null ">create_time=#{creatTime},</if>
        <if test="updateTime !=null ">update_time=#{updateTime}</if>
 
        where id=#{id}
 
    </update>
 
    <!--动态语句-->
    <select id="list" resultType="org.example.mybatis.pojo.User">
        select * from emp
        <where>
 
            <if test="name !=null">
                name like concat('%',#{name},'%')
            </if>
 
            <if test="gender !=null">
                and gender = #{gender}
            </if>
 
            <if test="begin !=null and end !=null ">
                and entrydate between #{begin} and #{end}
            </if>
 
        </where>
 
        order by update_time desc
    </select>
 
</mapper>

写在Mapper接口里的

package org.example.mybatis;
 
 
import org.example.mybatis.mapper.UserMapper;
import org.example.mybatis.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
 
@SpringBootTest //springboot整合单元测试的注解
class MybatisApplicationTests {
 
    @Autowired
    //声明接口类型的对象 将此对象注入进来
    private UserMapper userMapper;
 
 
 
    @Test
    public void testList() {
//        List<User> userList = userMapper.list("张", (short) 1,
//                LocalDate.of(2010, 1, 1),
//                LocalDate.of(2020, 1, 1));
        List<User> userList =userMapper.list("张",null,null,null);
        System.out.println(userList);
    }
 
    @Test
    //动态更新员工数据 更新ID为14的员工 更新Username name gender
        public void testUpdata() {
 
        User user = new User();
 
        user.setId(13);
        user.setUsername("Dduo1");
        user.setName("多多");
        user.setGender((short) 1);
        user.setCreatTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
 
        //执行新增员工信息的操作
        userMapper.update(user);
    }
 
}

数据库中ID为13的员工信息完成了更新

set标签

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--复制引用-->
<mapper namespace="org.example.mybatis.mapper.UserMapper">
 
    <update id="update">
        <!--动态更新SQL-->
        update emp
        <!--用来替换set关键字 可以更新所有的标签并去除逗号-->
        <set>
            <if test="username !=null ">username=#{username},</if>
            <if test="password !=null ">password=#{password},</if>
            <if test="name !=null ">name=#{name},</if>
            <if test="gender !=null ">gender=#{gender},</if>
            <if test="image !=null ">image=#{image},</if>
            <if test="job !=null ">job=#{job},</if>
            <if test="deptID !=null ">dept_id=#{deptID},</if>
            <if test="entryDate !=null ">entrydate=#{entryDate},</if>
            <if test="creatTime !=null ">create_time=#{creatTime},</if>
            <if test="updateTime !=null ">update_time=#{updateTime}</if>
        </set>
        where id=#{id}
 
    </update>
 
    <!--动态语句-->
    <select id="list" resultType="org.example.mybatis.pojo.User">
        select * from emp
        <where>
 
            <if test="name !=null">
                name like concat('%',#{name},'%')
            </if>
 
            <if test="gender !=null">
                and gender = #{gender}
            </if>
 
            <if test="begin !=null and end !=null ">
                and entrydate between #{begin} and #{end}
            </if>
 
        </where>
 
        order by update_time desc
    </select>
 
</mapper>

小结

foreach标签

循环遍历

动态SQL

xml文件里映射

在测试里面调用方法

传入形参集合

遍历集合

拿到集合里的每一个元素

然后拼接SQL语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--复制引用-->
<mapper namespace="org.example.mybatis.mapper.UserMapper">
 
    
 
    <!--批量删除员工信息-->
    <!--delete from emp where id  in (2,3)-->
    <delete id="deleteByIds">
        <!--
            collection 遍历的集合
            item 遍历出来的集合
            separator 分隔符
            open 遍历开始前拼接的SQL片段
            close 遍历结束后拼接的SQL片段
            标签体内写要遍历的元素
        -->
        delete from emp where id  in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
 
    </delete>
 
   
 
</mapper>

mapper接口

package org.example.mybatis.mapper;
 
import org.apache.ibatis.annotations.*;
import org.example.mybatis.pojo.User;
 
import java.time.LocalDate;
import java.util.List;
 
@Mapper//表示当前是Mybatis的一个接口 此时程序运行时框架会自动生成实现类对象(代理对象) 并交给spring的ioc容器
public interface UserMapper {
 
   
 
    //批量删除员工
    public void deleteByIds(List<Integer> ids);
 
}

测试类

package org.example.mybatis;
 
 
import org.example.mybatis.mapper.UserMapper;
import org.example.mybatis.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
@SpringBootTest //springboot整合单元测试的注解
class MybatisApplicationTests {
 
    @Autowired
    //声明接口类型的对象 将此对象注入进来
    private UserMapper userMapper;
    
    @Test
    //批量删除员工3 4 5
    public void testDeleteByIds(){
        List<Integer> ids= Arrays.asList(3,4,5);
 
        userMapper.deleteByIds(ids);
    }
 
 
}

小结

sql include标签

配套使用

看这个配置了两条SQL的映射文件

将代码抽取 抽取一部分SQL片段

然后需要SQL时再引入

sql标签负责抽取SQL

include负责引用片段

组件封装

总结

目录
相关文章
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
1625 5
|
SQL 缓存 Java
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
本文详细介绍了MyBatis的各种常见用法MyBatis多级缓存、逆向工程、分页插件 包括获取参数值和结果的各种情况、自定义映射resultMap、动态SQL
1034 1
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
1067 2
|
缓存 前端开发
后端MultipartFile接收文件转Base64
后端MultipartFile接收文件转Base64
707 5
|
存储 SQL API
探索后端开发:构建高效API与数据库交互
【10月更文挑战第36天】在数字化时代,后端开发是连接用户界面和数据存储的桥梁。本文深入探讨如何设计高效的API以及如何实现API与数据库之间的无缝交互,确保数据的一致性和高性能。我们将从基础概念出发,逐步深入到实战技巧,为读者提供一个清晰的后端开发路线图。
|
存储 SQL 数据库
深入浅出后端开发之数据库优化实战
【10月更文挑战第35天】在软件开发的世界里,数据库性能直接关系到应用的响应速度和用户体验。本文将带你了解如何通过合理的索引设计、查询优化以及恰当的数据存储策略来提升数据库性能。我们将一起探索这些技巧背后的原理,并通过实际案例感受优化带来的显著效果。
404 4
|
存储 前端开发 Java
Java后端如何进行文件上传和下载 —— 本地版(文末配绝对能用的源码,超详细,超好用,一看就懂,博主在线解答) 文件如何预览和下载?(超简单教程)
本文详细介绍了在Java后端进行文件上传和下载的实现方法,包括文件上传保存到本地的完整流程、文件下载的代码实现,以及如何处理文件预览、下载大小限制和运行失败的问题,并提供了完整的代码示例。
6535 2
|
SQL 安全 Go
SQL注入不可怕,XSS也不难防!Python Web安全进阶教程,让你安心做开发!
在Web开发中,安全至关重要,尤其要警惕SQL注入和XSS攻击。SQL注入通过在数据库查询中插入恶意代码来窃取或篡改数据,而XSS攻击则通过注入恶意脚本来窃取用户敏感信息。本文将带你深入了解这两种威胁,并提供Python实战技巧,包括使用参数化查询和ORM框架防御SQL注入,以及利用模板引擎自动转义和内容安全策略(CSP)防范XSS攻击。通过掌握这些方法,你将能够更加自信地应对Web安全挑战,确保应用程序的安全性。
525 4
|
前端开发 IDE 数据库连接
ThinkPHP6 模型层的模型属性,表映射关系,以及如何在控制层中使用模型层和模型层中的简单CRUD
本文详细介绍了ThinkPHP6中模型层的使用,包括模型属性设置、表映射关系、以及如何在控制层中使用模型层进行CRUD操作。
ThinkPHP6 模型层的模型属性,表映射关系,以及如何在控制层中使用模型层和模型层中的简单CRUD