mybatis动态SQL多条件查询1 - if 标签

Mybatis框架的动态SQL技术是一种根据特定条件动态拼接SQL语句的过程。它的存在是为了解决拼接SQL语句字符串的痛点问题。创建新的Mapper接口和新的mapper映射文件。

1.创建DynamicSqlMapper接口

package com.mybatis.mapper;

import com.mybatis.pojo.Emp;

import java.util.List;

/**
 * @author 大力pig
 * @date 2022/05/07
 */
public interface DynamicSqlMapper {
    /**
     * 多条件查询员工信息
     */
    List<Emp> getEmpByCondition(Emp emp);
}

2.创建DynamicSqlMapper映射文件

if test标签后不需要写原来的${}或者#{}

<?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.mybatis.mapper.DynamicSqlMapper">
    <!--        List<Emp> getEmpByCondition(Emp emp);-->
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp where
        <if test="empName != null and empName != ">
            emp_name = #{empName}
        </if>
        <if test="age != null and age != ">
            and age = #{age}
        </if>
        <if test="sex != null and sex != ">
            and sex = #{sex}
        </if>
        <if test="email != null and email != ">
            and email = #{email}
        </if>
    </select>
</mapper>

3.测试类

4.测试结果

5. 引伸 : 其中一样传入信息不符合

5.1 and后的参数不提供

and后的参数是只, 如上图mapper映射文件中, age, sex, email

我们将age和email都设置成null, 在运行一次,看看效果。

List<Emp> emps = mapper.getEmpByCondition(new Emp(null, "张三", null, "男", null));

5.1.1运行效果

总结: and后的参数不提供, 不会影响sql运行,而且我们从LOG中可以看出,and后设置成null的参数,就不会参与sql运行。

5.2 where后的参数不提供

5.2.1 运行效果

运行错误,我们可以从log里看出, where后跟的是and,那么sql语法肯定是错误的。

5.2.2 解决方法

在mapper映射文件中where语句后添加恒成立的条件 1=1, 映射文件如下。

<select id="getEmpByCondition" resultType="Emp">
        select * from t_emp where 1=1
        <if test="empName != null and empName != ">
            emp_name = #{empName}
        </if>
        <if test="age != null and age != ">
            and age = #{age}
        </if>
        <if test="sex != null and sex != ">
            and sex = #{sex}
        </if>
        <if test="email != null and email != ">
            and email = #{email}
        </if>
    </select>

运行结果: 成功运行且不报错。我们可以从LOG看出,恒成立条件1=1之后拼接and就不会报错。

6. 总结

恒成立1=1的作用:

1. where后跟着的参数是null的时候方便拼接sql

2.当参数都是null时候,sql也可以成功运行。

动态SQL中:

if 标签根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到sql中去

经验分享 程序员 微信小程序 职场和发展