Mybatis(三) 动态sql
1.动态sql意义
mybatis核心是对sql语句进行灵活的操作控制并通过表达式来判断,对sql语句进行灵活的拼接和组织。
2.sql片段
sql 片段为了提高sql语句的可重用性,一些重复的查询操作可以将其放入sql片段中,实现sql语句块的重用。
*例如复合查询语句,通过id,name,sex等进行查询,多个statement中都有可能包含这一部分复合查询操作(查询用户列表,查询满足需求的记录总条数都会用到)。*可以将这一部分判断、筛选条件放入sql片段中进行重用。
<sql id="SQL片段唯一标识">
.....sql语句块
</sql>
**where语句不要放入sql片段中:**一个statement可能会调用多个sql片段 但不该包含多个where。
如何引用片段:
3.动态sql where if foreach
1)where + if
便于理解:
<!--statement中-->
<select 省略。。。>
<!--基本的固定查询语句 例如-->
select * from tb_User
<where>
<!--包装类型,包含user对象-->
<!--判断语句写在test值中-->
<if test="user!=null">
<if test="user.sex!=null and user.sex!=''">
and user.sex=#{user.sex}
</if>
<if test="user.其他属性=null and user.sex!=默认属性/认为未赋值的无效属性">
and user.其他属性=#{user.其他属性}
</if>
</if>
</where>
</select>
where 块将会将子元素中的第一条判断语句的and自动清除
上面的sql语句可重用较高部分 适合放在sql 片段中
<if test="user!=null">
<if test="user.sex!=null and user.sex!=''">
and user.sex=#{user.sex}
</if>
<if test="user.其他属性=null and user.sex!=默认属性/认为未赋值的无效属性">
and user.其他属性=#{user.其他属性}
</if>
</if>
2)foreach
这一部分主要解决问题,多值传递(使用集合或数组),例如判断where 字段名 in (xxx,xxx,xxxx)或 where 字段名=xx or…
首先包装类型包含一个集合(或数组)idList,测试方法也为这个集合完成赋值。查询id在这个集合中的用户的信息
<sql id="search_from_list">
<if test="idList!=null">
<foreach collection="idlist" item="userId" open="and (" closs=")" separator="or">
<!--collection: 集合名-->
<!--item userId 每次遍历所赋值元素-->
<!--open 遍历开始插入语句-->
<!--close 遍历结束插入语句-->
<!--separator 每次遍历后(最后一次除外),插入语句 也就是两次遍历中间插入语句-->
id=#{userId}
<foreach/>
</if>
</sql>
实现了or查询方式
in 查询方式: 简单替换 open=“and id in(” close=")" separator=","
显而易见拼接结果 and id in (值1,值,值2,值3)