一、什么是动态sql
1、定义:
根据不同条件拼接sql语句,实现对数据库的精准操作
2、实现
sqlMapper.xml或注解
二、SqlMapper.xml文件中常用的动态SQL元素
<if>、<choose>、<when>、<otherwise>、<sql>、<include>、<where>、<set>、<trim>、<foreach>、<bind>
1、<if>
- 用于条件判断
- 当OGNL表达式为true时拼接在语句中,为false则会忽略被该标签包裹的内容
- 多个条件时,每个标签内的条件前加add
- 因为if标签在条件不成立时,不会自动去掉where和add,所以在where后写1=1,当以上情况发生时,条件衡成立
<select id="findStudent" resultType="student"
parameterType="student">
select * from student
where 1=1
<if test="ssex !=null">
and ssex=#{ssex}
</if>
<if test="classid !=0">
and classid=#{classid}
</if>
</select>
2、<choose><when><otherwise>
- 多条件分支判断
- when标签可以有多个,当when中的OGNL条件表达式成立时,则不走下一个when标签
- oherwise类似defult,以上when条件都不成立时,就走otherwise中,当不写otherwise并且以上条件都不满足时,就是全查
<select id="findStudentChoose" resultType="student" parameterType="student"> select * from student where 1=1 <choose> <when test="sname != null">and sname=#{sname}</when> <when test="birthday !=null">and birthday=#{birthday}</when> <when test="ssex !=null"> and ssex=#{ssex}</when> <when test="classid !=0">and classid=#{classid}</when> </choose> </select>
3、<sql>
- 在xml文件中,单独定义一个sql片段,封装sql片段
- 可以封装sql