一、动态sql简介以及使用场景
在现实场景中,我们在进行物品选择的时候,通过不同的筛选条件 实现我们的目标选择。
同样在数据库进行有针对性对象的选择的时候,我们也可以根据sql语句的不同条件进行精准操作。即,根据不同标签组合sql语句。
实现方式: ①映射配置文件xml;②注解;
常用的动态sql元素:
<if 、choose、otherwise、when、set、where、trim、foreach、bind>
二、映射配置文件xml-- 动态sql中的元素标签
1、<if>标签
if是 判断语句,用于单条件分支判断;在查询、删除、修改的时候会使用到.
<select id="findStu" 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>
if 标签的 test 属性值是一个符合 OGNL 的表达式, 表达式可以是 true 或 false。如果为true就会被选择,如果是false,自动被省略不会被选择。
另外,if标签在条件不成立时,不会自动去掉where和add,所以在where后写1=1这个条件,让条件恒成立。
2、<choose>标签
<select id="findChoose" resultType="Student" parameterType="Student">
select <include refid="ziduansql"></include> 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"