简介
where 标签主要用来简化 SQL 语句中的条件判断,可以自动处理 AND/OR 条件。
在if标签和choose-when-otherwise标签的案例中,SQL语句加入了一个条件’1=1’,它既保证了where后面的条件成,页避免了where后面出现的第一个词语是and 或者or之类的关键字。
假设把条件‘1=1’去掉,可以出现以下语句
select * from t_customer where and username like concat('%','#{username}','%')
上面语句因为出现了where后直接是and,在sql运行时会报语法错误。
这个时候可以使用where标签处理
语法
<where>
<if test="判断条件">
AND/OR ...
</if>
</where>
if 语句中判断条件为 true 时,where 关键字才会加入到组装的 SQL 里面,否则就不加入。where 会检索语句,它会将 where 后的第一个 SQL 条件语句的 AND 或者 OR 关键词去掉。
网络案例
<select id="selectWebsite" resultType="net.biancheng.po.Website">
select id,name,url from website
<where>
<if test="name != null">
AND name like #{name}
</if>
<if test="url!= null">
AND url like #{url}
</if>
</where>
</select>
where标签-完整案例
1.数据库准备
# 创建一个名称为t_customer的表
CREATE TABLE t_customer (
id int(32) PRIMARY KEY AUTO_INCREMENT,
username varchar(50),
jobs varchar(50),
phone varchar(16)
);
# 插入3条数据
INSERT INTO t_customer VALUES ('1', 'joy', 'teacher', '13733333333');
INSERT INTO t_customer VALUES ('2', 'jack', 'teacher', '13522222222');
INSERT INTO t_customer VALUES ('3', 'tom', 'worker', '15111111111');
2.新建项目或Module
3 pom.xml中添加
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mybatis</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.biem</groupId>
<artifactId>dynamaicSql</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--1.引入mybatis包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis