什么是动态SQL?
动态SQL是根据参数条件动态拼接而成的SQL语句, 与写死的SQL语句不同, 动态SQL更加灵活.
动态SQL有什么?
<where...if>, <set...if> ,<foreach>, <sql&include>等等
怎么用?
where...if 用于条件查询
不确定where关键字有几个条件的时使用
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<!--test表示条件, 表示uid!=nul时添加uid条件, 第一个条件会自动去掉and关键字-->
<if test="uid != null">
and uid = #{uid}
</if>
<if test="name != null">
and name = #{name}
</if>
</where>
</select>
set...if和where...if用法差不多, 但是if中的条件是后面加上, 而不是前面加and
<update id="updateUserByCondition" parameterType="user">
update user
<set>
<if test="name != null">
name = #{name},
</if>
<if test="password != null">
password = #{password},
</if>
where uid = 1
</update>
foreach
foreach有三种方法:
- 数组 2. 集合 3. 封装到对象
最常用的是集合的方式
<select id="findUserByUids" resultType="user">
select * from user where uid in
<!--传入的参数以'('开头,以')'结尾, 用','分割-->
<foreach collection="collection" item="uid" open="(" close=")" separator=",">
#{uid}
</foreach>
</select>