一、动态sql,比如说利用sql查询年龄为21,姓名为“jcc”的人。
<select id="queryByNameOrASqlTag" parameterType="Person" resultType="Person">
select id,name,age,sex from person where
<if test="name !=null and name!=‘‘">
name = #{name}
</if>
<if test="age !=null and age!=0">
and age = #{age}
</if>
</select>
在select标签中,可以写上条件语句判断,name与age是否为空。
如果出现name为空的情况,sql为:select id ,name ,age,sex from person where and age = 21,那么运行测试类就会出现sql语句报错。
第一种方法可以在where后面写一句1=1,就是不论你name和age是不是空sql都会执行成功。
第二种方法:在select标签中添加where标签,该标签会自动识别删除第一个and,不会处理后面的and。
<select id="queryByNameOrASqlTag2" parameterType="Person" resultType="Person">
select id,name,age,sex from person
<where>
<if test="name !=null and name!=‘‘">
and name = #{name}
</if>
<if test="age !=null and age!=0">
and age = #{age}
</if>
</where>
</select>
原文:https://www.cnblogs.com/jccjcc/p/13961395.html