Mybatis 动态SQL
多条件查询语句
if元素
if元素的test属性表示进入if内需要满足的条件
<select id="">
SELECT * FROM smbms_bill WHERE id=id
<if test="name != null">
AND productName LIKE CONCAT('%',#{name},'%')
</if>
</select>
where元素
where 元素主要用来简化SQL语句中的where 条件判断,并能智能地处理and 和 or 不必担心多余关键字导致语法错误。
<select id="select" resultType="User">
SELECT * FROM smbms_user
<where>
<if test="name != null">
AND proName LIKE CONCAT('%',#{name},'%')
</if>
<if test="code != null">
AND proCode LIKE CONCAT('%',#{code},'%')
</if>
</where>
</select>
SQL片段
SQL元素标签用来定义可重复使用的SQL代码片段,使用时只需要用include元素标签引用即可,最终达到SQL语句重用的目的
<!-- 建立SQL片段 -->
<sql id="select">
<!-- test: 条件是对入参进行判断 -->
<if test="name != null">
AND proName LIKE CONCAT('%',#{name},'%')
</if>
<if test="code != null">
AND proCode LIKE CONCAT('%',#{code},'%')
</if>
</sql>
<!-- 使用include引用sql片段 -->
<select id="allProviderLikenameLikecode">
SELECT * FROM `smbms_provider`
<where>
<include refid="select"></include>
</where>
</select>
<!-- 引用其它mapper.xml的sql片段 -->
<include refid="namespace.sql片段"/>
Mybatis处理sql中的大于,小于,大于等于,小于等于
Mybatis中SQL语句中的“<” 和 “>” 要用转义字符 “<” 和 “>” ,否则会报错!
(在Mybatis中 “=” 符号不需要转义)
大于等于:>=
小于等于:<=
如查询年龄大于等于指定年龄的用户信息;
<select id="id" ...>
select * from smbms_user where id >= #{id}
</select>
set+if元素 (用于修改)
set主要用于更新操作,它的主要功能和where元素差不多,主要是在包含的语句前输出一个set ,若包含的语句是以逗号结束的,会自动把逗号忽略掉,在配合if元素就可以动态的更新需要修改的字段;而不需要修改的字段,则可以不再被更新。
使用set标签不仅可以动态地配置set关键字,还可以剔除追加到条件末尾的任何不相关的逗号(因为在update语句中使用if标签,若后面的的if没有执行,则导致在语句末尾残留多余的逗号)。
<update id="updateBill" parameterType="Bill">
update smbms_bill
<set>
<if test="billCode != null ">billCode=#{billCode},</if>
<if test="productName != null ">productName=#{productName},</if>
<if test="productDesc != null ">productDesc=#{productDesc},</if>
<if test="proid != null ">proid=#{proid},</if>
<if test="proName != null ">proName=#{proName},</if>
<if test="productUnit != null ">productUnit=#{productUnit}</if> <!-- 最后一个“,” 逗号建议不要写 -->
</set>
<!-- 这里也可以使用<where>元素和<if>元素 来进行验证判断 -->
where id=#{id}
</update>
if+trim的使用(不常用)
<update id="update">
update smbms_bill
<!--
prefix="set" 前缀,作用是通过自动识别是否有返回值后,在trim包括的内容上加上前缀,也可以是where
suffixOverrides="," 后缀,作用是在trim包含的内容上加上后缀
prefixOverrides="and | or" 对于trim包含内容的首部进行制定内容如”and | or“ 的忽略
suffix="where id= #{id}" 对于trim 包含的内容的首位部进行指定内容的忽略
-->
<trim prefix="set" suffixOverrides="," suffix="where id= #{id}">
<if test="billCode != null ">billCode=#{billCode},</if>
<if test="productName != null ">productName=#{productName},</if>
<if test="productDesc != null ">productDesc=#{productDesc},</if>
<if test="proid != null ">proid=#{proid},</if>
<if test="proName != null ">proName=#{proName},</if>
<if test="productUnit != null ">productUnit=#{productUnit}</if> <!-- 最后一个“,” 逗号建议不要写 -->
</trim>
</update>