MyBatis——动态SQL

  • 1、动态 SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作
  • 2、动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似
  • 3、MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作

什么时候需要用到动态SQL呢

在这里插入图片描述
看电影时我们可以选择地区,类型,规格,年份等等,我们可以同时选择不确定个选项(比如说只选地区,或者选类型和年份)
这个时候常规的SQL(SQL语句固定)已经无法满足我们的需求,我们的SQL语句现在是不确定的,这时我们需要用到动态SQL
其实动态SQL也不难,简单来说就是动态拼接一个字符串,mybatis为我们提供了一些标签来帮助我们更简单的实现动态SQL

1、if和where

  • where标签就相当于SQL语句中的where
  • if用于判断
<select id="queryEmp" resultType="Employee">
	select * from employee
	<where>
		<if test="id != null">
			and id=#{id}
		</if>
		<if test="gender != null and gender.trim()!=''">
			and gender=#{gender}
		</if>
	</where>
</select>

2、trim

  • prefix: 添加前缀
  • prefixOverrides: 去掉前缀(合理的去掉,即如果需要就不去,如果不需要就不去掉)
  • suffix: 添加后缀
  • suffixOverrides: 去掉后缀
<select id="queryEmp" resultType="Employee">
	select * from employee
	<trim prefix="where" prefixOverrides="and">
		<if test="id != null">
			and id=#{id}
		</if>
		<if test="email != null and email.trim()!=''">
			and email=#{email}
		</if>
	</trim>
</select>

3、set

  • 主要是用于解决修改操作中SQL语句中可能多出逗号的问题(set后面的列用逗号隔开,set标签会帮你去掉多余的,)
<update id="update">
	update employee
	<set>
		<if test="email  != null and email.trim()!=''">
			email=#{email},
		</if>
		<if test="gender  != null and gender.trim()!=''">
			gender=#{gender},
		</if>
	</set>
	where id=#{id}
</update>

4、choose(when、otherwise)

  • choose 主要是用于分支判断,类似于java中的switch case,只会满足所有分支中的一个
<select id="queryEmp" resultType="Employee">
	select * from employee
	<where>
		<choose>
			<when test="id != null">
				and id=#{id}
			</when>
			<when test="gender != null and gender.trim()!=''">
				and gender=#{gender}
			</when>
			<otherwise>
				 last_name = '李四'
			</otherwise>
		</choose>
	</where>
</select>

5、foreach

  • foreach 主要用于循环迭代
    • collection: 要迭代的集合
    • item: 当前从集合中迭代出的元素
    • open: 开始字符
    • close:结束字符
    • separator: 元素与元素之间的分隔符
    • index:
      • 迭代的是List集合: index表示的当前元素的下标
      • 迭代的Map集合: index表示的当前元素的key
  •    select * from employee where id in (1,2,5)
    
<select id="queryEmpList" resultType="Employee">
	select * from employee where id in 
	<foreach collection="list" item="id" open="(" separator="," close=")">
		#{id}
	</foreach>
</select>

6、sql

  • sql 标签是用于抽取可重用的sql片段,将相同的,使用频繁的SQL片段抽取出来,单独定义,方便多次引用
  • 使用include标签refid属性引入sql
<sql id="selectSQL">
	select * from employee 
</sql>
<select id="queryEmp" resultType="Employee">
	<include refid="selectSQL"></include>
	<where>
		<choose>
			<when test="id != null">
				and id=#{id}
			</when>
			<when test="gender != null and gender.trim()!=''">
				and gender=#{gender}
			</when>
			<otherwise>
				 last_name = '李四'
			</otherwise>
		</choose>
	</where>
	
</select>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值