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

目录

1.创建DynamicSqlMapper接口

2.创建DynamicSqlMapper映射文件

3.测试类

4.测试结果

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

5.1 and后的参数不提供

 5.1.1运行效果

5.2 where后的参数不提供

5.2.1 运行效果

5.2.2 解决方法

6. 总结


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.测试类

    @Test
    public void testGetEmpByCondition(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicSqlMapper mapper = sqlSession.getMapper(DynamicSqlMapper.class);
        List<Emp> emps = mapper.getEmpByCondition(new Emp(null, "张三", 32, "男", "123@qq.com"));
        System.out.println(emps);
    }

4.测试结果

11:08:49:276 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 1234250905.
11:08:49:292 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==>  Preparing: select * from t_emp where emp_name = ? and age = ? and sex = ? and email = ?
11:08:49:338 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 张三(String), 32(Integer), 男(String), 123@qq.com(String)
11:08:49:390 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <==      Total: 1
[Emp{eid=1, empName='null', age=32, sex='男', email='123@qq.com', dept=null}]

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运行效果

11:22:57:465 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 769530879.
11:22:57:496 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==>  Preparing: select * from t_emp where emp_name = ? and sex = ?
11:22:57:622 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 张三(String), 男(String)
11:22:57:763 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <==      Total: 1
[Emp{eid=1, empName='null', age=32, sex='男', email='123@qq.com', dept=null}]

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

5.2 where后的参数不提供

        List<Emp> emps = mapper.getEmpByCondition(new Emp(null, null, 32, "男", "123@qq.com"));

5.2.1 运行效果

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

1:25:12:513 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 769530879.
11:25:12:513 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==>  Preparing: select * from t_emp where and age = ? and sex = ? and email = ?
11:25:12:670 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 32(Integer), 男(String), 123@qq.com(String)

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and age = 32
         
         
            and sex = '男'
         
         ' at line 4

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就不会报错。

11:32:01:649 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 769530879.
11:32:01:649 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==>  Preparing: select * from t_emp where 1=1 and age = ? and sex = ? and email = ?
11:32:01:727 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 32(Integer), 男(String), 123@qq.com(String)
11:32:01:806 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <==      Total: 1
[Emp{eid=1, empName='null', age=32, sex='男', email='123@qq.com', dept=null}]

6. 总结

恒成立1=1的作用:

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

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

动态SQL中:

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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐