常用的动态sql使用
一、sql片段
组装sql我们不得不提到sql片段。就是我们可以把共有的一些sql语句抽离出来,组成sql片段。其他的statement就可以对其进行引用。
定义sql片段:
-
<sql id="query_user_where"> -
<if test="userCustom!=null"> -
<if test="userCustom.sex!=null and userCustom.sex!=''"> -
and user.sex=#{userCustom.sex} -
</if> -
</if> -
</sql>
引用sql片段,只需引用sql片段的id名称即可:
-
<!-- 用户信息综合查询 --> -
<select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom"> -
select * from user -
<where> -
<include refid="query_user_where"></include> -
</where> -
</select>
二、动态SQL元素
1.if
-
<select id="findUserById" resultType="user"> -
select * from user where -
<if test="id != null"> -
id=#{id} -
</if> -
and isDelete=0; -
</select>
这个是有问题的,如果id为null,那么sql语句就成了“select * from userwhere and isDelete = 0”
所以就有了where这个元素
2.where
-
<select id="findUserById" resultType="user"> -
select * from user -
<where> -
<if test="id != null"> -
id=#{id} -
</if> -
and isDelete=0; -
</where> -
</select>
3.foreach
当我们查询条件为数组或者List时,我们用foreach解析。比如传入多个用户id查询用户信息
(1)传入List
-
<select id="selectUserByList" parameterType="java.util.List" resultType="user"> -
select * from user -
<where> -
<!-- 传递List --> -
<if test="list!=null"> -
<foreach collection="list" item="item" open="and id in("separator=","close=")"> -
#{item.id} -
</foreach> -
</if> -
</where> -
</select>
item:为数组每个元素的名称,名称随意定义
open:循环开始
close:循环结束
separator:中间分隔输出
(2)传入数组
-
<select id="selectUserByArray" parameterType="Object[]" resultType="user"> -
select * from user -
<where> -
<!-- 传递数组 --> -
<if test="array!=null"> -
<foreach collection="array" index="index" item="item" open="and id in("separator=","close=")"> -
#{item.id} -
</foreach> -
</if> -
</where> -
</select>
index:为数组下标
4.set
-
<update id="updateUser" parameterType="com.dy.entity.User"> -
update user set -
<if test="username != null"> -
name = #{username}, -
</if> -
<if test="password != null"> -
password = #{password}, -
</if> -
<if test="age != null"> -
age = #{age} -
</if> -
<where> -
<if test="id != null"> -
id = #{id} -
</if> -
and isDelete = 0; -
</where> -
</update>
这几个是比较常用的,还有跟switch相似的choose和otherwise,还有trim,这里就不一一介绍了。大家有兴趣可以了解一下。
浙公网安备 33010602011771号