Mybatis动态SQL语句查询,实现一个参数 可查询多个字段。

简介: Mybatis动态SQL语句查询,实现一个参数 可查询多个字段。

案例如下图所示:

eaa5cce937c8488eb66a3fafa02e99d4.png

实现 根据 登录名 姓名  邮箱  查询

一. 以下代码用  姓名 地址 模糊查询xml代码如下

<select id="queryClientList" resultType="com.lt.crm.vo.QueryClient.QueryDeliveryClientVo">
        select
        a.CUSTOMERSNO "customersno",
        a.CUSTOMERSNAME "customersname",
        a.COMMUNITY "community",
        a.CUSTOMERSTEL "customerstel"
        from CRM_CUSTOMERS a
        <where>
            <if test="integratedQuery != null and integratedQuery != ''">
                1=1 and a.customersname like concat(concat('%',#{integratedQuery}),'%') or  a.community like concat(concat('%',#{integratedQuery}),'%')
            </if>
            <if test="customersno != null and customersno != ''">
                and a.customersno like '%'||#{customersno}||'%'
            </if>
            <if test="customersname != null and customersname != ''">
                and a.customersname like '%'||#{customersname}||'%'
            </if>
            <if test="community != null and community != ''" >
                and a.community like '%'||#{community}||'%'
            </if>
        </where>
    </select>

二. 最重要的就是这一行:

<if test="integratedQuery != null and integratedQuery != ''">
       1=1 and a.customersname like concat(concat('%',#{integratedQuery}),'%') or  a.community like concat(concat('%',#{integratedQuery}),'%')
</if>

1. 动态sql中 where 1=1

1. where 1=1,因为它总是ture ,执行计划就会忽略这个条件,Oracle、MySQL 结果都一样。


2. 为了避免:条件A判断出错 或者 往条件A传值时,传了空值,导致sql报错。


3. where1=1不影响SQL性能,也不会导致索引失效。SQL优化器已经将where1=1过滤了。

2.解释:


1. a.customersname like concat(concat('%',#{integratedQuery}),'%')  这是查 名字


2. a.community like concat(concat('%',#{integratedQuery}),'%')           这是查 地址


3. 两个字段 写到 一个 if 里面   用关键函数 or 将 他们 关联


4. 定义一个 新的 字段 integratedQuery  这个字段是 前端给后端传值的字段  


5. 对应的dao service serviceImpl实现层  controller 都加上 (integratedQuery) 这个字段


integratedQuery  这个字段 也要在我们的实体类里 定义   我用的是VO 我就写Vo类里 如下:


b160aa84229f4ed38fc93c77fbda78e6.png


目录
相关文章
|
7天前
|
SQL 缓存 Java
mybatis 一对多查询
mybatis 一对多查询
16 0
|
14天前
|
SQL
MyBatis-Plus-Join关联查询
MyBatis-Plus-Join关联查询
|
14天前
|
SQL XML Java
MyBatis-Plus多表关联查询
MyBatis-Plus多表关联查询
|
3天前
|
SQL Java 数据库连接
mybatis动态sql
mybatis动态sql
|
4天前
|
SQL 前端开发
基于jeecgboot复杂sql查询的列表自定义列实现
基于jeecgboot复杂sql查询的列表自定义列实现
10 0
|
6天前
|
SQL Java 数据库连接
MyBatis #与$的区别以及动态SQL
MyBatis #与$的区别以及动态SQL
10 0
|
6天前
|
XML Java 数据库连接
MyBatis 解决上篇的参数绑定问题以及XML方式交互
MyBatis 解决上篇的参数绑定问题以及XML方式交互
8 0
|
7天前
|
SQL Java 数据库连接
【mybatis】动态sql之批量增删改查
【mybatis】动态sql之批量增删改查
11 0
|
8天前
|
SQL 数据库
SQL数据库基础语法-查询语句
SQL数据库基础语法-查询语句
|
8天前
T-sql 高级查询( 5*函数 联接 分组 子查询)
T-sql 高级查询( 5*函数 联接 分组 子查询)