mybatis系列(二) mybatis动态SQL

1425 1.5~2.0 分钟 686

位于映射文件中, 提供 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>