后端数据库开发高级之通过在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负责引用片段

组件封装

总结

目录
相关文章
|
1月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
17天前
|
SQL 调度 数据库
开发YashanDB数据库?用 DBeaver for YashanDB 更顺手
数据库开发复杂易错,尤其在企业级场景中。为提升效率,YashanDB 团队基于 DBeaver 开源工具打造专属解决方案——DBeaver for YashanDB。它支持多类型数据库对象管理(表、视图、函数等),适配 YashanDB 特有表结构(HEAP、LSC),提供智能补全、语法高亮、SQL 调试等功能,让开发更高效流畅。推荐用于数据库应用开发团队、高频调试用户及中大型企业统一工具栈场景。
|
17天前
|
SQL 数据可视化 IDE
开发数据库不想写命令?YashanDB Developer Center 帮你轻松搞定
YashanDB Developer Center(YDC)是一款可视化的数据库开发工具,专为提升数据库开发效率而设计。它通过图形化对象管理让数据库对象清晰可见,提供智能SQL编辑器支持语法高亮与自动补全,实现PL调试的图形化操作,帮助快速定位问题。此外,操作记录可追溯,多端灵活部署,适配多种场景。无论是中大型企业研发团队,还是不熟悉命令行的业务开发者,YDC都能显著优化开发体验,堪称YashanDB的“可视化IDE”。
|
1月前
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
4月前
|
存储 JSON 测试技术
【HarmonyOS Next开发】云开发-云数据库(二)
实现了云侧和端侧的云数据库创建、更新、修改等操作。这篇文章实现调用云函数对云数据库进行增删改查。
99 9
【HarmonyOS Next开发】云开发-云数据库(二)
|
3月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
154 2
|
4月前
|
SQL 关系型数据库 API
HarmonyOs开发:关系型数据库封装之增删改查
每个方法都预留了多种调用方式,比如使用callback异步回调或者使用Promise异步回调,亦或者同步执行,大家在使用的过程中,可以根据自身业务需要进行选择性调用,也分别暴露了成功和失败的方法,可以针对性的判断在执行的过程中是否执行成功。
169 13
|
4月前
|
存储 前端开发 关系型数据库
鸿蒙开发:实现键值数据库存储
对于数据量比较的小的,我们直接选择轻量级的用户首选项方式即可,而对于数据量比较大的情况下,直接可以使用数据库,而对于相对来说,比较大的数据,我们就可以使用键值型数据库方式
159 2
|
4月前
|
SQL 关系型数据库 MySQL
MySQL导入.sql文件后数据库乱码问题
本文分析了导入.sql文件后数据库备注出现乱码的原因,包括字符集不匹配、备注内容编码问题及MySQL版本或配置问题,并提供了详细的解决步骤,如检查和统一字符集设置、修改客户端连接方式、检查MySQL配置等,确保导入过程顺利。
|
5月前
|
缓存 前端开发
后端MultipartFile接收文件转Base64
后端MultipartFile接收文件转Base64
139 5

热门文章

最新文章

下一篇
oss创建bucket