Mybatis动态 sql用法

什么叫动态SQL

如果嵌入的SQL没有明确给出,如在Java中定义了一个字符串类型的变量sql:String sql;,然后采用preparedStatement对象的execute方法去执行这个sql,该sql的值可能等于从文本框中读取的一个SQL或者从键盘输入的SQL,但具体是什么,在编译时无法确定,只有等到程序运行起来,在执行的过程中才能确定,这种SQL叫做动态SQL。

下面我将介绍编写动态aql语句时候经常用到的标签及实例

<if>标签 执行条件判断,成立则拼接,不成立则忽略

<select id="findStudentif" parameterType="Student" resultType="Student">
		<include refid="stusql"></include>
		
		where 1=1
		<if test="ssex != null">
		and ssex=#{ssex}
		</if>
		<if test="classid != 0">
		and classid = #{classid}
		</if>

<choose>标签 满足条件的语句 

<otherwise>满足其他条件的语句

<select id="findStudentChoose" parameterType="Student" resultType="Student" >
		<include refid="stusql"></include> where 1=1
	<choose>
		<when test="classid!=0"> classid = #{classid}</when>
		<when test="sname!=null"> sname = #{sname}</when>
		
		<otherwise>and sid=21</otherwise>
	</choose>

<where>标签 

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入
<select id="findStudentWhere" parameterType="Student"
		resultType="Student">
		<include refid="stusql"></include>
		<!-- 1.没有任何条件的时候,where整体不出现 2. 3. -->
		<where>
			<if test="ssex != null">
				and ssex=#{ssex}
			</if>
			<if test="classid != 0">
				and classid = #{classid}
			</if>
		</where>
	</select>

<set>标签 

set 标签元素主要是用在更新操作的时候,它的主要功能和 where 标签元素其实是差不多的,主是在包含的语句前输出一个 set,然后如果包含的语句是以逗号结束的话将会 把该逗号忽略,如果 set 包含的内容为空的 话则会出错。有了 set 元素就可以动态的更新那些修改了的字段
<update id="updateStudent" parameterType="student">
	update student
	<set>
		<if test="sname!=null">
			sname = #{sname},
		</if>
		<if test="birthday!=null">
			birthday = #{birthday},
		</if>
		<if test="ssex!=null">
			ssex = #{ssex},
		</if>
		<if test="classid!=0">
			classid = #{classid},
		</if>
	</set>
	<where>sid = #{sid}</where>
</update>

<trim>标签

<!-- trim 万能标签 preix 开头 suffix结尾 能代替where标签 set标签 -->
	<update id="updateStudentBysid" parameterType="student">
		update student
		<trim prefix="set" suffixOverrides=",">
			<if test="sname!=null">
				sname = #{sname},
			</if>
			<if test="birthday!=null">
				birthday = #{birthday},
			</if>
			<if test="ssex!=null">
				ssex = #{ssex},
			</if>
			<if test="classid!=0">
				classid = #{classid},
			</if>
		</trim>
		<where>sid=#{sid}</where>
	</update>

<foreach>标签

	<select id="findStudentArray" resultType="student">
		select * from student where sid in
		<foreach collection="array" item="s" open="(" separator=","
			close=")">
			#{s}
		</foreach>
	</select>

以上结束↑

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值