MyBatis动态SQL
动态SQL是MyBatis强大的特征之一,极大的简化了我们SQL拼装的操作,使用基于OGNL的表达式让操作更加简化
- OGNL对象图导航语言。强大的表达式语言,通过它可以非常方便的操作对象属性
动态SQL就是通过一系列的标签来决定输出的数据,完成SQL语句的组装
sql标签
(先说一个sql标签,这个不是动态sql)
将一些通用的SQL语句进行抽取,放到sql标签中,然后使用include标签将该SQL语句引入
<!--将表中的字段都拿出来放到一个单独的sql标签中,定义一个唯一的id-->
<sql id="user_common">
id,username,password,state,email,source,create_time,remark
</sql>
<select id="findAll" resultType="User">
<!--使用include标签获取sql标签中的sql语句-->
select <include refid="user_common"></include> from t_user;
</select>
在实际开中,即使是查询表中所有字段,也不建议使用select * ··· ,会影响查询效率,建议将需要的列名一一列出
现在简单的来看三个最常用的标签,使用它们来实现动态sql
where和if标签
当我们需要根据一些条件查询时,但是又不确定条件的个数时,就可以使用where标签加if标签
<select id="findUser" parameterType="User" resultType="User">
select * from t_user
<where>
<!--如果id不为空的话,标签中的sql片段,就加入到where条件中-->
<if test="id!=null">
or id=#{id}
</if>
<if test="username!=null and username!=''">
or username like #{username}
</if>
</where>
</select>
where标签能自动为sql语句加上where关键字
当where标签中只有一个if条件成立时,他也能够为我们自动的省略前面的or
foreach标签
当我们使用in查询出多行符合条件的数据时,因为in中的个数也不确定,这个时候就可以使用foreach标签
foreach标签可以达到遍历数据的效果,那么对于集合、数组等的遍历写法就会有些不同
foreach标签中的属性:
- collection:遍历传入的数据集,如果参数是集合,值固定为list
- open:遍历前的组合sql语句
- close:遍历后的组合sql语句
- separator:每一个遍历出来的数据中间分隔符
- item:代表遍历出的元素
foreach的三中用法:
1.传入集合
当我们传入的数据是一个包含多个id值的集合时:
<!-- 传入的参数是一个集合时,parameterType的值必须为list-->
<select id="findByIdList" parameterType="list" resultType="User">
select id,username from user
<!-- collection值必须为list-->
<foreach collection="list" open="where id in(" close=")" item="item" separator=",">
#{item}
</foreach>
</select>
最后组合成的sql语句就是:
select id,username from user where id in(id1,id2,id3···)
2.传入数组
当我们传入的是一个包含多个id值的数组时:
<!--注意这时的parameterType必须是一个 数组的类型[] -->
<select id="findByIdArray" parameterType="Integer[]" resultType="User">
select id,username from t_user
<!-- collection 必须为array-->
<foreach collection="array" open="where id in(" close=")" item="item" separator=",">
#{item}
</foreach>
</select>
3.传入POJO对象
当我们需要遍历的是对象中一个属性时(该属性是一个集合类型):
<!-- 这时传入的参数是一个对象-->
<select id="findByIdPojo" parameterType="Vo" resultType="User">
select id,username from t_user
<!-- collection的值对应的是该对象的属性名 该属性要是一个集合类型的-->
<foreach collection="idList" open="where id in(" close=")" item="item" separator=",">
#{item}
</foreach>
</select>
最后还有几个用来实现动态sql的标签
- set
- 动态配置关键字
- choose
- 按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则choose结束。类似switch
- trim
- 可以在该标签包含的内容前加上某些前缀或在其后加上某些后缀,也可以覆盖首部和尾部的某些内容