动态
Sql
是指
MyBatis
对
Sql
语句进行灵活操作,通过表达式进行判断,对
Sql
进行灵活拼接、组装。
例如:
- 我们要查询姓名中带 M 和 高于 1000的员工信息;
- 可能有时候我们需要不带条件查询;
- 可能有时候我们需要模糊查询;
- 可能有时候需要根据多条件查询;
- 动态SQL可以帮助我们解决这些问题。
- 通过Mybatis提供的各种标签方法实现动态拼接sql
if标签
mapper文件:
<select
id
=
"selectUseIf"
parameterType
=
"com.gs.entity.Emp"
resultType
=
"com.gs.entity.Emp"
>
select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
where
<!--
注意:判断条件中使用的变量为实体类或输入参数的属性
空字符串的判断仅能使用在字符串类型的属性中
-->
<if
test
=
"ename != null and ename != ''"
>
ename like concat('%',#{ename},'%')
</if>
<if
test
=
"sal != null"
>
and sal=#{sal}
</if>
<if
test
=
"deptno != null"
>
and deptno=#{deptno}
</if>
</select>
测试:
<select
id
=
"selectUseIf"
parameterType
=
"com.gs.entity.Emp"
resultType
=
"com.gs.entity.Emp"
>
select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
where
<!--
注意:判断条件中使用的变量为实体类或输入参数的属性
空字符串的判断仅能使用在字符串类型的属性中
-->
<if
test
=
"ename != null and ename != ''"
>
ename like concat('%',#{ename},'%')
</if>
<if
test
=
"sal != null"
>
and sal=#{sal}
</if>
<if
test
=
"deptno != null"
>
and deptno=#{deptno}
</if>
</select>
where标签
mapper文件:
<select
id
=
"selectUseWhere"
parameterType
=
"com.gs.entity.Emp"
resultType
=
"com.gs.entity.Emp"
>
select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
<where>
<if
test
=
"ename != null and ename != ''"
>
ename like concat('%',#{ename},'%')
</if>
<if
test
=
"sal != null"
>
and sal=#{sal}
</if>
<if
test
=
"deptno != null"
>
and deptno=#{deptno}
</if>
</where>
</select>
测试:
@Test
public
void
testWhere
() {
SqlSession sqlSession
=
MybatisUtil
.
getSession
();
EmpMapper empMapper
=
sqlSession
.
getMapper
(
EmpMapper
.
class
);
Emp emp
=
new
Emp
();
emp
.
setEname
(
"S"
);
emp
.
setSal
(
1300.0
);
emp
.
setDeptno
(
20
);
List
<
Emp
>
list
=
empMapper
.
selectUseWhere
(
emp
);
for
(
Emp e
:
list
) {
System
.
out
.
println
(
e
);
}
sqlSession
.
close
();
}