mybatis 动态SQL
什么是动态SQL,为什么要使用动态SQL
举一个简单的例子
需求:根据用户的性别和用户名多条件查询用户信息。
对于这个需求可以写出这样一个mapper的配置
<select id="queryUserBySexAndUsername" resultType="user" parameterType="user">
select * from user where sex=#{sex} and username like #{username}
</select>
在这个配置中可以发现一个问题
如果我不是同时按照性别和用户名去查,而只是根据性别和用户名中的一个去查询甚至不给条件,上面的配置就不能使用了
就需要配置多个映射
如下
<select id="queryUserBySexAndUsername" resultType="user" parameterType="user">
select * from user where sex=#{sex} and username like #{username}
</select>
<select id="queryUserBySex" resultType="user" parameterType="user">
select * from user where sex=#{sex}
</select>
<select id="queryUserUsername" resultType="user" parameterType="user">
select * from user where username like #{username}
</select>
<select id="queryUser" resultType="user" parameterType="user">
select * from user
</select>
那么这些配置就有很多重复的部分,而且不能使用同一个配置,就很不方便,动态sql就是来解决这个问题的
where和if标签
-
where标签:处理SQL语句,自动添加where关键字
-
if标签,test属性,判断表达式真假 , 具体查询的时候每个条件是and还是or直接写到if标签里面的sql里面
<select id="queryUserByWhere" resultType="user" parameterType="user">
select * from user
<where>
<if test="sex!=''and sex!=null">
and sex=#{sex}
</if>
<if test="username!=''and username!=null">
and username like #{username}
</if>
</where>
</select>
SQL标签
将SQL语句抽取,其他SQL语句中引入。
<!--
SQL片段抽取
使用include标签引入
-->
<sql id="commonsSql">
id,username,sex,birthday,address
</sql>
<select id="queryUserByWhere" resultType="user" parameterType="user">
<!-- include 标签引入列名-->
select <include refid="userColumn"/> from user
<where>
<if test="username!='' and username != null">
and username like #{username}
</if>
<if test="sex!='' and sex!=null">
and sex = #{sex}
</if>
</where>
</select>

引入外部xml配置文件中的共享SQL片段时,使用namespace属性值+“.”+sql标签的id属性值。
迭代标签 foreach
有时候一个sql语句中的数据 来自一个列表 mybatis用foreach一个个获取 组成最终的sql
foreach标签遍历拼接SQL语句
- collection属性:遍历传入集合
- 当参数是集合时collection属性值固定为list
- 当参数是数组时collection属性值固定为array
- 当参数是pojo对象时 collection属性配置pojo中成员变量名
- open属性:遍历拼接前
- close属性:遍历拼接后
- separator属性:拼接的符号
- item属性:遍历到的元素
<delete id="deleteUserByArray" parameterType="int[]">
delete from user where id in
<foreach collection="array" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
<delete id="deleteUserByList" parameterType="list">
delete from user where id in
<foreach collection="list" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</delete>

浙公网安备 33010602011771号