MyBatis:简述MyBatis中动态sql的相关操作

MyBatis:简述MyBatis中动态sql的相关操作


MyBatis中用于实现动态SQL的元素有:
      a. if:用if实现条件的选择,用于定义where的字句的条件。
      b. choose(when,otherwise):相当于Java中的switch语句,通常when和otherwise一起使用。
      c. where:简化SQL语句中的where条件。
      d. set:解决SQL语句中跟新语句
      e. foreach:解决SQL语句中批量语句操作

1. 动态SQL-插入与删除语句-使用foreach

      详情见博客:https://blog.csdn.net/qq_29229567/article/details/84972319

2. 动态SQL-查询语句-使用if

<select>       
	select * from emp where 1=1
		<if test="deptNo!=null && deptNo!='' ">
			and deptno=#{deptNO}
		</if>
		<if test="deptName!=null && deptName!='' ">
			and deptno=#{deptName}
		</if>
</select>

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

3. 动态SQL-查询语句-使用choose

<select id="queryEmp"  resultType="cn.test.entity.Emp">
	select * from emp where 1=1
	<choose>
		<when test="deptNo!=null && deptNo!='' ">
			and deptno=#{deptNo}
		</when>
		<when test="deptName!=null && deptName!='' ">
			and deptname=#{deptName}
		</when>
		<otherwise>
			and personnum>#{personNum}
		</otherwise>
	</choose>
</select>

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

4. 动态SQL-查询语句-使用where

<select id="queryEmp"  resultType="cn.test.entity.Emp">
select * from emp
	<where>
		<if test="deptNo!=null && deptNo!='' ">
			and deptno=#{deptNO}
		</if>
		<if test="deptName!=null && deptName!='' ">
			and deptno=#{deptName}
		</if>
	</where>
</select>

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

5. 动态SQL-更新语句-使用set结合if

<update id="updateEmp" parameterType="com.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: 》无效字符的异常

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小二(海阔天空)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值