Mybatis 动态SQL条件查询(注释和XML方式都有)

 

需求 : 根据用户的输入情况进行条件查询

新建了一个 userInfo2Mapper 接口,然后写下如下代码,声明 selectByCondition 这个方法

package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserInfo2Mapper {
   
    List<UserInfo> selectByCondition(UserInfo userInfo);
}

我们先用XML的方式实现

在resources 中创建 Userinfo2XMLMapper.xml 文件

 将 Userinfo2XMLMapper.xml 文件中的 namespace 进行修改,改为 userInfo2Mapper 接口中的第一行 package 的内容再加上接口名

然后补充如下代码,用户输入什么条件,什么条件就不为空,就可以根据该条件进行查询

<?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.example.mybatisdemo.mapper.UserInfo2Mapper">
    <select id="selectByCondition" resultType="com.example.mybatisdemo.model.UserInfo">
        select * from userinfo
        where
        <if test="username!=null">
            username = #{username}
        </if>
        <if test="age!=null">
            and age = #{age}
        </if>
        <if test="gender!=null">
            and gender = #{gender}
        </if>
    </select>
</mapper>

再回到接口,然后Generate,test,勾选selectByCondition,ok

然后补充代码

package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

@Slf4j
@SpringBootTest
class UserInfo2MapperTest {
    @Autowired
    private UserInfo2Mapper userInfo2Mapper;
  
    @Test
    void selectByCondition() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("io");
        userInfo.setAge(23);
        userInfo.setGender(0);
        List<UserInfo> userInfos = userInfo2Mapper.selectByCondition(userInfo);
        log.info(userInfos.toString());
    }
}

然后我的数据库里面是有这些数据的

接下来我们执行看看结果 ,没毛病

 接下来我们对代码稍作修改,我们不 set gender了,再看看运行结果

package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

@Slf4j
@SpringBootTest
class UserInfo2MapperTest {
    @Autowired
    private UserInfo2Mapper userInfo2Mapper;
  
    @Test
    void selectByCondition() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("io");
        userInfo.setAge(23);
        //userInfo.setGender(0);
        List<UserInfo> userInfos = userInfo2Mapper.selectByCondition(userInfo);
        log.info(userInfos.toString());
    }
}

也是可以正常运行的,比限制 gender 多了一条数据 

但是当我们把setUsername也给去掉,只查询年龄为23的人,发现报错了

 我们看日志会发现,多了一个and

这时候我们就要用 trim 标签来消除这个多余的and (上节博客也有trim的讲解)

然后我们回到 Userinfo2XMLMapper.xml 对代码进行修改,加上 trim 标签

<?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.example.mybatisdemo.mapper.UserInfo2Mapper">
    <select id="selectByCondition" resultType="com.example.mybatisdemo.model.UserInfo">
        select * from userinfo
        where
        <trim prefixOverrides="and">
            <if test="username!=null">
                username = #{username}
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
            <if test="gender!=null">
                and gender = #{gender}
            </if>
        </trim>
    </select>
</mapper>

这时再次运行程序就能成功啦

另一种方法就是 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.example.mybatisdemo.mapper.UserInfo2Mapper">
    <select id="selectByCondition" resultType="com.example.mybatisdemo.model.UserInfo">
        select * from userinfo
        <where>
            <if test="username!=null">
                username = #{username}
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
            <if test="gender!=null">
                and gender = #{gender}
            </if>
        </where>
    </select>
</mapper>

这也是可以成功运行的 

用 where 还是 用 trim 都可以,这两个没啥差别 

但是 trim 标签有个问题就是,如果所有where条件都为null的时候,会报错,因为where后面没东西了

where 标签就不会有上面的问题 ,如果查询条件均为空,直接删除 where 关键字

如果一定要用 trim 标签也有一种解决方式

接下来我们看看如何用注释的方式实现

在 UserInfo2Mapper 接口中写入下面的代码,跟XML代码差不多
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserInfo2Mapper {
   
    @Select("<script>" +
            "select * from userinfo" +
            "        <where>" +
            "            <if test='username!=null'>" +
            "                username = #{username}" +
            "            </if>" +
            "            <if test='age!=null'>" +
            "                and age = #{age}" +
            "            </if>" +
            "            <if test='gender!=null'>" +
            "                and gender = #{gender}" +
            "            </if>" +
            "        </where>"+
            "</script>")
    List<UserInfo> selectByCondition2(UserInfo userInfo);
}

然后就,右键,Generate,test,勾选 selectByCondition2,ok,然后补充下面代码,也跟XML一样

package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@Slf4j
@SpringBootTest
class UserInfo2MapperTest {
    @Autowired
    private UserInfo2Mapper userInfo2Mapper;

    @Test
    void selectByCondition2() {
        UserInfo userInfo = new UserInfo();
        //userInfo.setUsername("io");
        userInfo.setAge(23);
        //userInfo.setGender(0);
        List<UserInfo> userInfos = userInfo2Mapper.selectByCondition(userInfo);
        log.info(userInfos.toString());
    }
}

运行试试,没毛病 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

接口测试介绍以及用例编写

6.1 接口 6.1.1 接口概述 定义&#xff1a; 接口就是API&#xff08;Application Programming Interface&#xff0c;应用程序接口&#xff09;&#xff0c;是一个软件或服务对外提供的接口&#xff0c;别人只要调用这接口&#xff0c;而内部如何实现&#xff0c;不需要关心。…

Python 算法交易实验67 第一次迭代总结

说明 在这里对第一次迭代&#xff08;2023.7~ 2024.1&#xff09;进行一些回顾和总结&#xff1a; 回顾&#xff1a; 1 实现了0~1的变化2 在信息隔绝的条件下&#xff0c;无控制的操作&#xff0c;导致被套 总结&#xff1a; 思路可行&#xff0c;在春暖花开的时候&#x…

3分钟带你了解,软件测试是做什么的

&#x1f525; 交流讨论&#xff1a;欢迎加入我们一起学习&#xff01; &#x1f525; 资源分享&#xff1a;耗时200小时精选的「软件测试」资料包 &#x1f525; 教程推荐&#xff1a;火遍全网的《软件测试》教程 &#x1f4e2;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1…

springboot集成COS对象存储

1.申请腾讯云存储桶 新建密钥&#xff08;后面配置要用到&#xff09; 2.编写工具类 此处使用工具类进行基本属性配置&#xff0c;也可选择在yml中配置 package com.sfy.util;import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.a…

【网络安全 -> 防御与保护】专栏文章索引

为了方便 快速定位 和 便于文章间的相互引用等 作为一个快速准确的导航工具 网络安全——防御与保护 &#xff08;一&#xff09;.信息安全概述

地图 - 实现有多条定位,显示多条定位,并且使用一个圆形遮罩层将多条定位进行覆盖

首先&#xff0c;需要在你的index.html模板页面头部加载百度地图JavaScript API代码&#xff0c;密钥可去百度地图开放平台官网申请 <script type"text/javascript" src"//api.map.baidu.com/api?typewebgl&v1.0&ak您的密钥"></script&…

消息队列之王——Kafka

Zookeeper 在学习kafka之前&#xff0c;我们需要先学习Zookeeper&#xff0c;那Zookeeper是什么呢&#xff1f;Zookeeper是一个开源的分布式的&#xff0c;为分布式框架提供协调服务的Apache项目。 Zookeeper 工作机制 Zookeeper从设计模式角度来理解&#xff1a;是一个基于观…

VUE---插槽

一、插槽的作用&场景 1、在封装组件的时候&#xff0c;将可变的结构设计为插槽&#xff08;<slot></slot>&#xff09; 2、使用上述组件的时候&#xff0c;可以按需为插槽提供自定义的结构&#xff0c;以达到复用组件且高度自定的效果 二、基本语法 1、组件内…

2024年【广东省安全员B证第四批(项目负责人)】新版试题及广东省安全员B证第四批(项目负责人)作业模拟考试

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 广东省安全员B证第四批&#xff08;项目负责人&#xff09;新版试题参考答案及广东省安全员B证第四批&#xff08;项目负责人&#xff09;考试试题解析是安全生产模拟考试一点通题库老师及广东省安全员B证第四批&…

在CentOS 7中配置 RAID服务

实验过程 Xnode1克隆虚拟机raid ps&#xff1a; 阿里云盘Xnode1获取 xnode1 https://www.alipan.com/s/HgLXfoeBWG2 提取码: eb70 编辑虚拟机 添加2硬盘 CRT连接&#xff08;root密码&#xff1a;000000&#xff09; 创建raid 0 [rootdemo ~]# lsblk 安装mdadm [rootdemo…

Facebook直播指南:教你如何轻松控评

Facebook直播在促进互动、扩大影响力、实时报道、创造内容和商业机会等方面都可以发挥很好的效果。无论是企业推广产品还是个人博主提升人气&#xff0c;Facebook直播都是一个值得尝试的渠道。 但是在刚开始直播的时候&#xff0c;可能会遇到以下情况&#xff1a;想要通过Face…

Java项目:ssm框架基于spring+springmvc+mybatis框架的民宿预订管理系统设计与实现(ssm+B/S架构+源码+数据库+毕业论文)

一、项目简介 本项目是一套ssm827基于SSM框架的民宿预订管理系统设计与实现&#xff0c;主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调…

【数据结构与算法】之字符串系列-20240122

这里写目录标题 一、383. 赎金信二、387. 字符串中的第一个唯一字符三、389. 找不同四、392. 判断子序列五、409. 最长回文串 一、383. 赎金信 简单 给你两个字符串&#xff1a;ransomNote 和 magazine &#xff0c;判断 ransomNote 能不能由 magazine 里面的字符构成。 如果…

2、Line Charts折线图

可视化时间趋势 现在你已经熟悉了编码环境,是时候学习如何制作自己的图表了! 在本教程中,您将学习足够的Python来创建专业外观的折线图。然后,在接下来的练习中,您将使用您的最新技能处理真实世界的数据集。 本课程数据集夸克网盘下载链接:https://pan.quark.cn/s/a235ac…

微信公众号怎么申请超过2个

一般可以申请多少个公众号&#xff1f;目前公众号申请数量的规定是从2018年底开始实施的&#xff0c;至今没有变化。规定如下&#xff1a;1、个人可以申请1个个人主体的公众号&#xff1b;2、企业&#xff08;有限公司&#xff09;可以申请2个公众号&#xff1b;3、个体户可以申…

记录 js 过滤到tree上面的多余的数据

代码如下&#xff08;示例&#xff09;&#xff1a; filterTree(arr, ids,firsttrue) {if(first){//首次传入深度克隆数据防止修改源数据arrJSON.parse(JSON.stringify(arr))}let emptyArr [];for (let item of arr) {if (ids.includes(item.id)) {if (item.children &&am…

友元、隐式类型转化

友元提供了一种突破封装的方式&#xff0c;有时提供了便利。但是友元会增加耦合度&#xff0c;破坏了封装&#xff0c;所以友元不宜多用。 友元分为&#xff1a;友元函数和友元类 &#xff08;一&#xff09;友元函数 友元函数可以直接访问类的私有成员&#xff0c;它是定义在…

L1-058 6翻了(Java)

“666”是一种网络用语&#xff0c;大概是表示某人很厉害、我们很佩服的意思。最近又衍生出另一个数字“9”&#xff0c;意思是“6翻了”&#xff0c;实在太厉害的意思。如果你以为这就是厉害的最高境界&#xff0c;那就错啦 —— 目前的最高境界是数字“27”&#xff0c;因为这…

JVM系列-1.初识JVM

&#x1f44f;作者简介&#xff1a;大家好&#xff0c;我是爱吃芝士的土豆倪&#xff0c;24届校招生Java选手&#xff0c;很高兴认识大家&#x1f4d5;系列专栏&#xff1a;Spring原理、JUC原理、Kafka原理、分布式技术原理、数据库技术、JVM原理&#x1f525;如果感觉博主的文…

【QT+QGIS跨平台编译】之二:【zlib+Qt跨平台编译】(一套代码、一套框架,跨平台编译)

文章目录 一、zlib介绍二、文件下载三、文件分析四、pro文件五、编译实践 一、zlib介绍 zlib是一套通用的解压缩开源库&#xff0c;提供了内存&#xff08;in-memory&#xff09;压缩和解压函数。zlib是一套通用的解压缩开源库&#xff0c;提供了内存&#xff08;in-memory&am…
最新文章