ssm框架之mybatis框架动态SQL
1 mybatis动态sql
mybatis可以通过各种各样的标签在sql映射文件中实现如下功能
1、语句的动态拼接
2、前后缀格式处理
3、复杂参数处理
常用标签如下:
1.1 if标签
如下示例,当有一个入参为null或者空的时候的时候,不参与计算,这种情况就应该使用if标签
<update id="updateWebsite">
update website
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="url != null and url != ''">
url = #{url},
</if>
<if test="age != null and age != ''">
age = #{age},
</if>
<if test="country != null and country != ''">
country = #{country},
</if>
</set>
where id = #{id}
</update>
1.2 where标签
如下示例,当使用where进行条件查询时候,可以用where标签,它可以把最前面的and去掉
<select id="selectByCondition" resultType="com.dts.entity.Website">
select * from website
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
<if test="country != null and country != ''">
and country like concat('%',#{country},'%')
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
</where>
</select>
1.3 choose标签
如下所示,类似于 java中的if else
<choose>
<when test="createtime != null and createtime != ''">
and createtime = #{createtime}
</when>
<otherwise>
and createtime is null
</otherwise>
</choose>
1.4 foreach标签
进行批量操作的时候,使用foreach标签
<select id="selectByIds" resultType="com.dts.entity.Website">
select * from website where id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
1.5 set标签
与if标签一起配合,可以去掉最后一个逗号
<update id="updateWebsite">
update website
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="url != null and url != ''">
url = #{url},
</if>
<if test="age != null and age != ''">
age = #{age},
</if>
<if test="country != null and country != ''">
country = #{country},
</if>
</set>
where id = #{id}
</update>
1.6 trim标签
trim标签比较复杂 它可以
动态地为SQL语句添加前后缀
智能忽略标签前后多余的and、or或逗号等字符
使用trim标签替换前面示例中的where标签
实现示例中相同的功能
使用trim标签替换前面示例中的set标签
实现示例中相同的功能