动态SQL

动态 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 ();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值