侧边栏壁纸
博主头像
Curllen博主等级

早上的云霞好美~

  • 累计撰写 12 篇文章
  • 累计创建 18 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

mybatis系列(二) mybatis动态SQL

Curllen
2018-11-01 / 0 评论 / 0 点赞 / 732 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-05-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

位于映射文件中,提供OGNL表达式动态生成SQL的功能.

动态SQL

  • if

判断语句, 例如判断是否输入用户名来拼接语句

<select id="queryUserListLikeUserName" resultType="User">
		select * from tb_user where sex=1
		<!-- if:判断
			test:OGNL表达式
			userName:接口文件中通过@param设定的参数名(下同)
			trim:字符串处理方法,去掉字符串起始和结尾的空格(JQuery也有相同方法)
		 -->
		<if test="userName!=null and userName.trim()!=''">
			 and user_name like '%' #{userName} '%'
		</if>
</select>
  • choose>when,otherwise(>,表示标签级别,>前面是父标签)

条件选择,例如是否输入用户名/年龄来拼接语句(选其一,只选择第一个符合条件(或都不符合情况下的otherwise)的语句进行拼接)

<select id="queryUserListLikeUserNameOrAge" resultType="User">
		select * from tb_user where sex=1 
		<!-- choose:条件选择
			when:test-判断条件,一旦有一个when成立,后续的when都不再执行
			otherwise:所有的when都不成立时,才会执行
		 -->
		<choose>
			<when test="userName!=null and userName.trim()!=''">and user_name like '%' #{userName} '%'</when>
			<when test="age != null">and age = #{age}</when>
			<otherwise>and user_name = 'zhangsan' </otherwise>
		</choose>
	</select>
  • where

条件选择,和if/choose配合使用,给sql拼接多个语句, 例如即输入了用户名也输入了年龄,全部拼接进SQL语句

<select id="queryUserListLikeUserNameAndAge" resultType="User">
		select * from tb_user
		<!-- 
			会在SQL语句中自动添加where关键字
			有一定的纠错功能:去掉sql语句块之前多余的一个and|or
			通常结合if或者choose使用
		 -->
		<where>
			<if test="userName!=null and userName.trim()!=''">user_name like '%' #{userName} '%'</if>
			<if test="age!=null">and age = #{age}</if>
		</where>
	</select>
  • set

更新信息,和if配合使用,当其中某个if不满足,则数据库不更新该字段,例如更新用户信息,sex=null

<update id="updateUserSelective" >
		UPDATE tb_user
		<!-- 
			会在SQL语句中自动添加set关键字
			也有一定的纠错功能:自动去掉sql语句块之后多余的一个逗号
			有关sex的if不通过,则数据库不更新sex的值
		 -->
		<set>
			<if test="userName!=null and userName.trim()!=''">user_name = #{userName},</if>
			<if test="password!=null and password.trim()!=''">password = #{password},</if>
			<if test="name!=null and name.trim()!=''">name = #{name},</if>
			<if test="age!=null">age = #{age},</if>
			<if test="sex!=null">sex = #{sex},</if>
			updated = now(),
		</set>
		WHERE
			(id = #{id});
	</update>
  • foreach

当参数是集合/数组(集合底层是可变数组),进行遍历(突破参数只能是基本数据类型,HashMap,pojo)

<select id="queryUserListByIds" resultType="User">
		select * from tb_user where id in 
		<!-- 
			foreach:遍历集合
			collection:接收的集合参数,接口文件中通过@param设定的参数名
			item:被遍历的集合中的一个元素
			separator:分隔符
			open:以什么开始(本例中,如果foreach已经被了'()'包围,则不用open和close
			close:以什么结束
		 -->
		<foreach collection="ids" item="id" separator="," open="(" close=")">
			#{id}
		</foreach>
	</select>
0

评论区