MyBatis(中)

news2024/10/2 12:17:12

1、动态sql:

1、if标签:

mapper接口:

//if 标签  多条件查询
    List<Car> selectByMultiConditional(@Param("brand") String brand,@Param("guidePrice") Double guidePrice,@Param("carType") String carType);

mapper映射文件:

 <select id="selectByMultiConditional" resultType="Car">
        select *
        from t_car
        where 1=1
        <!-- if标签中的test的属性是必须的
             if标签中的test的属性值是true或者是false
             如果是ture 拼接if标签里面的sql语句

             test属性中可以使用的数据:
             如果使用啦Param的注解  那么只能只用Param的注解里面的参数
             如果没有使用Param的注解的话,那么使用的是可以是Param1 param2... 或者arg0 arg1...

             如果传递的不是某一个属性值而是对象,那么可以使用的数据只能是对象里面的字段

        -->
        <if test="brand !=null and brand!=''">
           and brand like "%"#{brand}"%"
        </if>
        <if test="guidePrice !=null and guidePrice!=''">
            and guide_price > #{guidePrice}
        </if>
        <if test="carType !=null and carType!=''">
            and car_type =#{carType}
        </if>
    </select>

 测试类:

/**
     * 使用if标签多条件查询
     */
    @Test
    public void test1(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByMultiConditional(null,null,null);//什么参数也没有
        carList.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("--------------");
        List<Car> carList1 = mapper.selectByMultiConditional("保时捷", 100.0, null);//两个参数
        carList1.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("--------------");
        List<Car> carList2 = mapper.selectByMultiConditional("比亚迪", 25.0, "混动");
        carList2.forEach(car -> {
            System.out.println(car);
        });

2、where标签:

where标签的作用:让where子句更加动态智能。

  • 所有条件都为空时,where标签保证不会生成where子句。
  • 自动去除某些条件前面多余的and或or。

 mapper接口:

//if 和 where标签一起使用
    List<Car> selectByMultiConditionalWithWhere(@Param("brand") String brand,@Param("guidePrice") Double guidePrice,@Param("carType") String carType);

mapper映射文件:

 <select id="selectByMultiConditionalWithWhere" resultType="Car">
        select *
        from t_car
        <!--
            where 标签的使用可以使where的语句更加灵活
            如果所有的条件都不成立,那么就不会有where语句
            真好 也不用拼1=1 啦
        -->
        <where>
            <if test="brand !=null and brand!=''">
                and brand like "%"#{brand}"%"
            </if>
            <if test="guidePrice !=null and guidePrice!=''">
                and guide_price > #{guidePrice}
            </if>
            <if test="carType !=null and carType!=''">
                and car_type =#{carType}
            </if>
        </where>
 </select>

 测试类:

 /**
     * 使用if 和 where 标签多条件查询
     */
    @Test
    public void test2(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByMultiConditionalWithWhere(null,null,null);//什么参数也没有
        carList.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("--------------");
        List<Car> carList1 = mapper.selectByMultiConditionalWithWhere("保时捷", 100.0, null);//两个参数
        carList1.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("--------------");
        List<Car> carList2 = mapper.selectByMultiConditionalWithWhere("比亚迪", 25.0, "混动");
        carList2.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("--------------");
        List<Car> carList3 = mapper.selectByMultiConditionalWithWhere(null, 100.0, null);
        carList3.forEach(car -> {
            System.out.println(car);
        });
    }

总结:

        使用where的标签的话可以去where语句的前面的and或者or,但是不可去除条件语句的后面的and或者or 

3、 trim标签:

trim标签的属性:

  • prefix:在trim标签中的语句前添加内容
  • suffix:在trim标签中的语句后添加内容
  • prefixOverrides:前缀覆盖掉(去掉)
  • suffixOverrides:后缀覆盖掉(去掉)

mapper接口:

 <select id="selectByMultiConditionalWithTrim" resultType="Car">
        select *
        from t_car
        <!--
            prefix: 在trim标签的内容的前面加上 前缀
            suffix: 在trim标签的内容的后面加上 后缀
            prefixOverrides: 将删除trim标签 指定的前缀
            suffixOverrides: 删除trim标签 指定的后缀
        -->
        <trim prefix="where" suffixOverrides="or|and">
            <if test="brand !=null and brand!=''">
                 brand like "%"#{brand}"%" and
            </if>
            <if test="guidePrice !=null and guidePrice!=''">
                guide_price > #{guidePrice} and
            </if>
            <if test="carType !=null and carType!=''">
                car_type =#{carType}
            </if>
        </trim>
    </select>

测试和接大差不差,就不复制粘贴啦,主要是看Trim标签怎么使用的! 

4、set标签:

主要使用在update语句当中,用来生成set关键字,同时去掉最后多余的“,”

比如我们只更新提交的不为空的字段,如果提交的数据是空或者"",那么这个字段我们将不更新。

 mapper接口:

//set 标签  通常用于更新操作
    int updateCarWithSetById(Car car);

mapper映射文件:

<update id="updateCarWithSetById">
        update t_car
        <set>
            <if test="carNum != null and carNum != ''">car_num = #{carNum},</if>
            <if test="brand != null and brand != ''">brand = #{brand},</if>
            <if test="guidePrice != null and guidePrice != ''">guide_price = #{guidePrice},</if>
            <if test="produceTime != null and produceTime != ''">produce_time = #{produceTime},</if>
            <if test="carType != null and carType != ''">car_type = #{carType},</if>
        </set>
        where
        id =#{id}
    </update>

测试方法:

//测试 set标签
    @Test
    public  void test5(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.updateCarWithSetById(new Car(169L, "凯迪拉克", null, 12.5, null, "燃油"));
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

5、choose when otherwise:

语法格式:

<choose>
  <when></when>
  <when></when>
  <when></when>
  <otherwise></otherwise>
</choose>

相当于java中的if-else  只有一个分支会被执行!!

需求:先根据品牌查询,如果没有提供品牌,再根据指导价格查询,如果没有提供指导价格,就根据生产日期查询。

mapper接口:

//choose when otherwise
    /*需求:先根据品牌查询,如果没有提供品牌,再根据指导价格查询,如果没有提供指导价格,就根据生产日期查询。*/
    List<Car> selectByChoose (@Param("brand") String brand,@Param("guidePrice") Double guidePrice,@Param("produceTime") String produceTime);

mapper映射文件:

<select id="selectByChoose" resultType="Car">
        select *
        from t_car
        <where>
            <choose>
                <when test="brand != null and brand != ''">brand = #{brand}</when>
                <when test="guidePrice != null and guidePrice != ''">guide_price = #{guidePrice}</when>
                <otherwise>produce_time = #{produceTime}</otherwise>
            </choose>
        </where>
    </select>

 测试类:

//测试 choose when otherwise
    @Test
    public void test6(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByChoose("比亚迪汉", null, "2000-01-02");
        carList.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("-------------------");
        List<Car> carList1 = mapper.selectByChoose(null, 120.0, "2000-01-02");
        carList1.forEach(car -> {
            System.out.println(car);
        });
        System.out.println("-------------------");
        List<Car> carList2 = mapper.selectByChoose(null, null, "2000-01-02");
        carList2.forEach(car -> {
            System.out.println(car);
        });
    }

测试结果:

        这里的sql语句可以很直观的看出来,这个choose的特点就是只有一个条件会被执行,即使其传递的参数也符合要求。

6、模糊查询的写法:

方法一:
brand like '%${brand}%'
方法二:
brand like concat('%',#{brand},'%')
方式三:
brand like "%"#{brand}"%"

经常使用方式三!

 7、foreach标签:

(1)批量删除:

mapper接口:

 //foreach 通过ids来批量删除
    int deleteByIdsUseForeach(@Param("ids") Long[] ids);

 mapper映射文件:

<delete id="deleteByIdsUseForeach">
        delete
        from t_car
        <!--
            foreach 标签的属性 :
            collection 用来指定是数组还是集合
            item  代表数组或者集合中的元素
            separtor  循环之间的分割符

        -->
        where id in (
            <foreach collection="ids" item="id" separator="," >
                #{id}
            </foreach>
            )
    </delete>

小括号也可以不写 就是 in(....)

<delete id="deleteByIdsUseForeach">
        delete
        from t_car
        <!--
            foreach 标签的属性 :
            collection 用来指定是数组还是集合
            item  代表数组或者集合中的元素
            separtor  循环之间的分割符
            open:foreach标签中所有内容的开始
            close:foreach标签中所有内容的结束

        -->
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

测试类:

//测试批量删除
    @Test
    public void test7(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Long[] ids ={198L,199L,200L};
        int count = mapper.deleteByIdsUseForeach(ids);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1089451.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ATF(TF-A)之UBSAN动态代码分析

安全之安全(security)博客目录导读 目录 一、UBSAN简介 二、TF-A中UBSAN配置选项 一、UBSAN简介 未定义行为消毒器(Undefined Behavior Sanitizer&#xff0c;UBSAN)是Linux内核的未定义行为动态检测器。 详细信息可参考&#xff1a;https://github.com/google/kernel-sanit…

3D 生成重建007-Fantasia3D和Magic3d两阶段玩转文生3D

3D生成重建3D 生成重建007-Fantasia3D和magic3d 文章目录 0 论文工作1 论文方法1.1 magic3d1.2 Fantasia3D 2 效果2.1 magic3d2.2 fantasia3d 0 论文工作 两篇论文都是两阶段法进行文生3d&#xff0c;其中fantasia3D主要对形状和外表进行解耦&#xff0c;然后先对geometry进行…

第五章 图

第五章 图 图的基本概念图的应用背景图的定义和术语 图的存储结构邻接矩阵邻接表 图的遍历连通图的深度优先搜索连通图的广度优先搜索 图的应用最小生成树拓扑排序 小试牛刀 图的基本概念 图结构中&#xff0c;任意两个结点之间都可能相关&#xff1b;而在树中&#xff0c;结点…

接口自动化测试,完整入门篇

1. 什么是接口测试 顾名思义&#xff0c;接口测试是对系统或组件之间的接口进行测试&#xff0c;主要是校验数据的交换&#xff0c;传递和控制管理过程&#xff0c;以及相互逻辑依赖关系。其中接口协议分为HTTP,WebService,Dubbo,Thrift,Socket等类型&#xff0c;测试类型又主…

Web安全基础:常见的Web安全威胁及防御方法 |青训营

Web安全基础&#xff1a;常见的Web安全威胁及防御方法 在现代Web开发中&#xff0c;安全性至关重要。Web应用面临各种潜在的威胁&#xff0c;包括跨站脚本&#xff08;XSS&#xff09;、跨站请求伪造&#xff08;CSRF&#xff09;等。了解这些威胁以及如何防御它们&#xff0c…

c语言练习87:合并两个有序数组

合并两个有序数组 合并两个有序数组https://leetcode.cn/problems/merge-sorted-array/ 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2&#xff0c;另有两个整数 m 和 n &#xff0c;分别表示 nums1 和 nums2 中的元素数目。 请你 合并 nums2 到 nums1 中&#xff…

Excel 自动提取某一列不重复值

IFERROR(INDEX($A$1:$A$14,MATCH(0,COUNTIF($C$1:C1,$A$1:$A$14),0)),"")注意&#xff1a;C1要空置&#xff0c;从C2输入公式 参考&#xff1a; https://blog.csdn.net/STR_Liang/article/details/105182654 https://zhuanlan.zhihu.com/p/55219017?utm_id0

超越平凡:Topaz Photo AI for Mac带您领略人工智能降噪的魅力

在这个充满噪点和高频信息的时代&#xff0c;照片和视频的降噪成为了一个重要而迫切的需求。Mac用户现在有了一个强大的新工具——Topaz Photo AI for Mac&#xff0c;这是一款利用人工智能技术进行降噪和优化的软件。通过这款软件&#xff0c;您可以轻松地改善图像质量&#x…

呈现高效的软件测试技术 助力软件研发提升10倍质量

像大多数软件工程一样&#xff0c;软件测试是一门艺术。在过去十年中&#xff0c;自动化测试是测试软件的最佳方式。计算机可在瞬间运行数百个测试&#xff0c;而这样的测试集使公司能自信地每天发布数十个版本的软件。有大量资源(书籍、教程和在线课程)可用于解释如何进行自动…

金蝶EAS代码执行漏洞

【漏洞概述】 金蝶 EAS 及 EAS Cloud 是金蝶软件公司推出的一套企业级应用软件套件&#xff0c;旨在帮助企业实现全面的管理和业务流程优化。 【漏洞介绍】 金蝶 EAS 及 EAS Cloud 存在远程代码执行漏洞 【影响版本】 金蝶 EAS 8.0&#xff0c;8.1&#xff0c;8.2&#xf…

【Java学习之道】Java常用集合框架

引言 在Java中&#xff0c;集合框架是一个非常重要的概念。它提供了一种方式&#xff0c;让你可以方便地存储和操作数据。Java中的集合框架包括各种集合类和接口&#xff0c;这些类和接口提供了不同的功能和特性。通过学习和掌握Java的集合框架&#xff0c;你可以更好地管理和…

【python】anaconda中创建虚拟环境

创建虚拟环境 查看当前所有环境 首先打开Anaconda Prompt 初始进入的是base环境&#xff0c;如下。但是我们需要创建一个新的虚拟环境。 查看当前所有虚拟环境 conda env list 创建虚拟环境 conda create -n 虚拟环境名称 python3.10.1 这里使用conda create -n test python…

opencv dnn模块 示例(18) 目标检测 object_detection 之 pp-yolo、pp-yolov2和pp-yolo tiny

文章目录 1、PP-YOLO1.1、网络架构1.1.1、BackBone骨干网络1.1.2、DetectionNeck1.1.3、DetectionHead 1.2、Tricks的选择1.2.1、更大的batchsize1.2.2、滑动平均1.2.3、DropBlock1.2.4、IOU Loss1.2.5、IOU Aware1.2.6、GRID Sensitive1.2.7、Matrix NMS1.2.8、CoordConv1.2.9…

出差学知识No3:ubuntu查询文件大小|文件包大小|磁盘占用情况等

1、查询单个文件占用内存大小2、显示一个目录下所有文件和文件包的大小3、显示ubuntu所有磁盘的占用情况4、查看ubuntu单个包的占用情况 1、查询单个文件占用内存大小 使用指令&#xff1a;ls -lh 文件 2、显示一个目录下所有文件和文件包的大小 指令&#xff1a;du -sh* 3…

FastAdmin表格添加统计信息

如上图&#xff0c;在列表顶部添加订单统计信息&#xff0c;统计符合当前筛选条件的记录。 列表页html中&#xff1a; <div class"panel-body"><div id"myTabContent" class"tab-content"><div class"tab-pane fade active…

vue绑定style和class 对象写法

适用于&#xff1a;要绑定多个样式&#xff0c;个数确定&#xff0c;名字也确定&#xff0c;但不确定用不用。 绑定 class 样式【对象写法】&#xff1a; .box{width: 100px;height: 100px; } .aqua{background-color: aqua; } .border{border: 20px solid red; } .radius{bor…

vue单页面应用使用 history模式路由时刷新页面404的一种可能性

原先使用的是 hash模式路由&#xff0c;因为要结合qiankun进行微前端改造&#xff0c;改成了 history模式&#xff0c;结果页面刷新之后没有正确渲染组件。按照一般思路检查 nginx配置 try_files $uri $uri/ /index.html;也配置上了&#xff0c;还是有问题。 页面异常显示 问题…

通达信突破前高回踩选股公式,假突破的一种应对策略

对于突破型交易策略&#xff0c;经常遇到的问题就是股价突破了某个关键的压力位&#xff0c;但很快又回落到原来的区间&#xff0c;这也就是所谓的“假突破”。 对于假突破&#xff0c;我们可以从以下几个方面进行识别&#xff1a; 1、确认整体趋势&#xff0c;如果行情处于明…

暴力递归转动态规划(九)

题目 题有点难&#xff0c;但还挺有趣 有一个咖啡机数组arr[]&#xff0c;其中arr[i]代表每一个咖啡机冲泡咖啡所需的时间&#xff0c;有整数N&#xff0c;代表着准备冲咖啡的N个人&#xff08;假设这个人拿到咖啡后喝完的时间为0&#xff0c;拿手里咖啡杯即变空&#xff09;&a…

day05_数组

今日内容 另: return补充说明 0 数组复习 1 数组内存 2 数组其他声明方式 3 数组遍历 4 数组在方法中的使用 5 数组排序算法 0.1 复习 1 中文描述方法的定义 方法是一段功能代码,完成某些事情,是独立的有固定的写法 public static根据方法是否返回数据,来确定要不要设置返回值类…