动态SQL
使用动态 SQL可简化代码的开发,减少开发者的工作量,程序可以自动根据业务参数来决定 SQL的组成。
sql的内容是变化的,可以根据条件获取到不同的sql语句。主要是where部分发生变化。
动态sql的实现, 使用的mybatis提供的标签。
if标签
<select id="findByAccount" parameterType="com.yy.entity.Account"
resultType="com.yy.entity.Account">
select * from t_account where
<if test="id!=0">
id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</select>
if 标签可以自动根据表达式的结果来决定是否将对应的语句添加到 SQL中,如果条件不成立则不添加,如果条件成立则添加。
where标签
<select id="findByAccount" parameterType="com.yy.entity.Account"
resultType="com.yy.entity.Account">
select * from t_account
<where>
<if test="id!=0">
id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</where>
</select>
where 标签可以自动判断是否要删除语句块中的 and 关键字,如果检测到where 直接跟 and 拼接,则自动删除 and,通常情况下 if 和 where结合起来使用。
choose,when,otherwise标签
<select id="findByAccount" parameterType="com.southwind.entity.Account"
resultType="com.yy.entity.Account">
select * from t_account
<where>
<choose>
<when test="id!=0">
id = #{id}
</when>
<when test="username!=null">
and username = #{username}
</when>
<when test="password!=null">
and password = #{password}
</when>
<otherwise test="age!=0">
and age = #{age}
</otherwise>
</choose>
</where>
</select>
trim标签
<select id="findByAccount" parameterType="com.yy.entity.Account"
resultType="com.yy.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<if test="id!=0">
id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</trim>
</select>
trim 标签中的 prefifix 和 suffiffiffix 属性会被用于生成实际的 SQL语句,会和标签内部的语句进⾏拼接,如果语句前后出现了 prefifixOverrides或者 suffiffiffixOverrides 属性中指定的值,MyBatis框架会自动将其删除。
set标签
<update id="update" parameterType="com.yy.entity.Account">
update t_account
<set>
<if test="username!=null">
username = #{username},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="age!=0">
age = #{age}
</if>
</set>
where id = #{id}
</update>
set标签配合if标签一起用 一般用于修改语句 如果传递的参数为null那么就不会修改该列的值。
foreach标签
<select id="findByIds" parameterType="com.yy.entity.Account"
resultType="com.yy.entity.Account">
select * from t_account
<where><!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from user where 1=1 and id in (1,2,3)
-->
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>