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

这篇具有很好参考价值的文章主要介绍了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());
    }
}

然后我的数据库里面是有这些数据的Mybatis 动态SQL条件查询(注释和XML方式都有),mybatis,sql,windows

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

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

 接下来我们对代码稍作修改,我们不 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 多了一条数据 

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

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

 我们看日志会发现,多了一个andMybatis 动态SQL条件查询(注释和XML方式都有),mybatis,sql,windows

这时候我们就要用 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>

这时再次运行程序就能成功啦Mybatis 动态SQL条件查询(注释和XML方式都有),mybatis,sql,windows

另一种方法就是 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>

这也是可以成功运行的 

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

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

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

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

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

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

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

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

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

在 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());
    }
}

运行试试,没毛病 

Mybatis 动态SQL条件查询(注释和XML方式都有),mybatis,sql,windows文章来源地址https://www.toymoban.com/news/detail-814242.html

到了这里,关于Mybatis 动态SQL条件查询(注释和XML方式都有)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Mybatis xml中排序(order by)条件用#{}查询失败

    问题描述: 处理简单分页时,发现从外部传入的排序条件无法生效,但程序无报错,正常返回列表,只是排序条件不对; 原因: #{}表示一个占位符,当#{}传入的数据是一个字符串时,会自动将传入的数据加一个双引号。 解决方法: 使用${}将传入的数据直接显示生成在sql中

    2024年01月17日
    浏览(9)
  • Mybatis 动态 sql 是做什么的?都有哪些动态 sql?能简述动态 sql 的执行原理不?

            OGNL表达式         OGNL,全称为Object-Graph Navigation Language,它是一个功能强大的表达式语言,用来获取和设置Java对象的属性,它旨在提供一个更高的更抽象的层次来对Java对象图进行导航。         OGNL表达式的基本单位是\\\"导航链\\\",一般导航链由如下几个部

    2024年02月15日
    浏览(13)
  • Mybatis Plus之DQL(条件查询方式、查询投影、查询条件设定、字段映射与表名映射)

    Mybatis Plus之DQL(条件查询方式、查询投影、查询条件设定、字段映射与表名映射)

    增删改查四个操作中,查询是非常重要的也是非常复杂的操作,这块需要我们重点学习下,这节我们主要学习的内容有: 条件查询方式 查询投影 查询条件设定 字段映射与表名映射 1.1 条件查询的类 MyBatisPlus将书写复杂的SQL查询条件进行了封装,使用编程的形式完成查询条件的

    2024年02月05日
    浏览(9)
  • Mybatis—XML配置文件、动态SQL

    Mybatis—XML配置文件、动态SQL

    学习完Mybatis的基本操作之后,继续学习Mybatis—XML配置文件、动态SQL。 Mybatis的开发有两种方式: 注解 XML 之前学习的基本操作都是基于注解开发。使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就

    2024年02月06日
    浏览(13)
  • Mybatis-plus动态条件查询QueryWrapper的使用

    Mybatis-plus动态条件查询QueryWrapper的使用

    queryWrapper是mybatis plus中实现查询的对象封装操作类,可以封装sql对象,包括where条件,order by排序,select哪些字段等等,他的层级关系如下图: 2.1-案例一:根据name模糊查看未删除的用户列表信息 过滤条件: queryWrapper实现: 2.2-案例二:查看姓李的并且邮箱不为空的用户列表

    2024年02月14日
    浏览(13)
  • Mybatis从0到1 SQL注入 参数占位符 XML配置 动态SQL

    Mybatis从0到1 SQL注入 参数占位符 XML配置 动态SQL

    学习完mybatis入门后,我们继续学习mybatis基础操作。 需求说明: 根据资料中提供的《tlias智能学习辅助系统》页面原型及需求,完成员工管理的需求开发。 通过分析以上的页面原型和需求,我们确定了功能列表: 查询 根据主键ID查询 条件查询 新增 更新 删除 根据主键ID删除

    2024年02月16日
    浏览(14)
  • Mybatis-plus 配置自定义sql(.xml文件)查询语句的步骤

    Mybatis-plus 配置自定义sql(.xml文件)查询语句的步骤

    这是使用Mybatis-plus 的自动生成实体类代码生成.xml文件, 所以他会在java目录下,不在resources目录下 如果在java目录下的xml文件,需要分别配置application.yml和pom.xml文件 type-aliases-package:java目录下边的第一级包名 mapper-locations: classpath:映射器的地址: 类路径:也就是.xml所在的包名

    2024年02月16日
    浏览(15)
  • 【JaveWeb教程】(27)Mybatis的XML配置文件与Mybatis动态SQL 详细代码示例讲解

    【JaveWeb教程】(27)Mybatis的XML配置文件与Mybatis动态SQL 详细代码示例讲解

    Mybatis的开发有两种方式: 注解 XML 使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。 在Mybatis中使用XML映射文件方式开发,需要符合一定的规范: XML映射文件的名称

    2024年02月01日
    浏览(9)
  • MyBatis XML 映射文件中的 SQL 语句可以分为动态语句和静态语句

    目录 静态查询: 动态查询: 静态更新: 动态更新: 静态删除: 动态删除: 动态语句和静态语句在 MyBatis 中的作用如下: 静态查询: 静态查询是指在 SQL 语句中执行固定的查询操作,查询的条件和内容是预先确定的,不会随着用户输入或其他条件的改变而改变。以下是一

    2024年01月18日
    浏览(19)
  • MyBatis多表查询+动态sql

    MyBatis多表查询+动态sql

    在全局配置文件中中设置MyBatis执行日志 假设有一个用户表和文章表,实体类中一个关联关系。 用户实体类 文章实体类 如果想查询的结果包含UserInfo的信息就需要使用,⼀对⼀映射要使⽤ association 标签,因为一篇文章只能对应一个作者。 Controller控制器代码 Service服务层代码

    2023年04月19日
    浏览(16)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包