Mybatis中动态SQL多条件查询

mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件。

choose(when otherwise)相当于Java中的switch语句,通常when和otherwise一起使用。

where:简化SQL语句中的where条件。

set 解决SQL语句中跟新语句

我们课已通过几个例子来看一下这几个元素的运用场景:

if:

<select id="queryEmp"  resultType="cn.test.entity.Emp">

select * from emp where 1=1

<if test="deptNo!=null">

and deptno=#{deptNO}

</if>

<if test="deptName!=null">

and deptno=#{deptName}

</if>

</select>

注:<if test="deptNo!=null">中 的deptNo是指实体类中的属性或字段;

choose:

<select id="queryEmp"  resultType="cn.test.entity.Emp">

select * from emp where 1=1

<choose>

<when test="deptNo!=null">

and deptno=#{deptNo}

</when>

<when test="deptName!=null">

and deptname=#{deptName}

</when>

<otherwise>

and personnum>#{personNum}

</otherwise>

</choose>

</select>

注:上面也说了,choose相当于Java中的switch语句;当第一个when满足时;就只执行第一个when中的条件。当when中的条件都不满足时;就会执行默认的的;也就是otherwise中的语句。

where:

<select id="queryEmp"  resultType="cn.test.entity.Emp">

select * from emp

<where>

<if test="deptNo!=null">

and deptno=#{deptNO}

</if>

<if test="deptName!=null">

and deptno=#{deptName}

</if>

</where>

</select>

注: where下面第一个if语句中以and开头,也可以省略第一个and ,如果第一个if语句中有and;mybatis会将第一个and忽略。

set:

<update id="updateEmp" parameterType="cn.test.entity.Emp" flushCache="true">

update emp

<set>

<if test="empName!=null">empname=#{empName},</if>

<if test="job!=null">job=#{job}</if>

</set>

where empno=#{empNo}

</update>

注:  在mybatis中的SQL语句结尾不能加“;”,这样会导致mybatis无法识别字符;导致SQL语句的语法错误;出现 java.sql.SQLSyntaxErrorException: ORA-00911: 无效字符的错误。的异常。

动态SQL语句***

1)<if> 习惯按null来判断

2)where a. WHERE 1=1 b<where>去掉开头的and或者or

3)set,去掉最后的逗号,没有就不管

4)foreach 遍历,collection数组类型,item当前循环的实例,open开头的字符串,close结尾的字符串,separator分隔符。最常用用在in子查询串

<foreach collection="array" item="id" open="(" close=")" separator=",">

最新文章

  1. python3爬取1024图片
  2. Java数据类型和MySql数据类型对应表
  3. Cent0S 升级Python会带来的问题
  4. Centos7搭建需要mysql的网站
  5. 在一个老外微信PM的眼中,中国移动App UI那些事儿
  6. [llvm] Call the LLVM Jit from c program
  7. HDU 5288 OO’s Sequence
  8. [Effective C++ --023]宁以non-member、non-friend替换member函数
  9. nginx在mac下的安装与基本操作
  10. Android--Service之绑定服务交互
  11. 深入javascript——构造函数和原型对象
  12. Java 泛型具体解释
  13. CodeForces 626B Cards
  14. 关于学习方法的借鉴和有关C语言学习的调查
  15. Nodejs进阶:express+session实现简易身份认证
  16. [AHOI 2016初中组]迷宫
  17. 十进制转为x进制的递归代码
  18. Delphi 导出数据至Excel的7种方法【转】
  19. django select_related()和反射结合
  20. linux下svn导入新目录到svn服务器特定地址

热门文章

  1. QT中循环显示图片和简单的显示图片
  2. Go语言的指针的一些测试
  3. web前端-《手机移动端WEB资源整合》——meta标签篇
  4. centos7.5&amp;ubuntu18.10安装Google浏览器
  5. php-cgi segmentation fault nginx
  6. 35.Spark系统运行内幕机制循环流程
  7. gvim代码补全
  8. python excellent code link
  9. Luogu P2016 战略游戏(树形DP)
  10. 理解Python的迭代器(转)