1.为什么要使用动态SQL?
动态SQL最经典的使用场景就是条件查询
假设我们有个实体类User,他有三个属性:int id, String username, String password
数据库中也有一个对应的user表,它的三个字段也分别是id, username和password
如果用户通过三个分别代表id, username, password的下拉列表,要进行条件查询
那SQL应该怎么写?select * from user where id=#{id} and username=#{username} and password=#{password}
可以吗?
答案是不行,如果用户没有在下拉列表设置id的值,JVM会给它设置默认值0,SQL语句变为:
select * from user where id=0 and username=#{username} and password=#{password}
显然,我们的表中没有id为0的数据,所以什么也查不到
我们需要的效果是,当id为0时,去掉id = #{id}这部分的语句,使用动态SQL就可以解决这个问题
2.使用<if>标签实现条件查询
<!--返回类型和参数类型由于我们在SqlMapConfig.xml中配置了全限定名,所以简写-->
<select id="findByCondition" parameterType="User" resultType="User">
select * from user
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
3.使用<foreach>标签实现动态in语句
如果外部传来一个int[] nums = {1, 2, 3, 4}该语句就会变为:sql select * from user where id in (1,2,3,4)
<select id="findByIds" parameterType="list" resultType="User">
<include refid="selectUser"></include>
<where>
<foreach collection="list" open="id in(" close=")" item="x" separator=",">
#{x}
</foreach>
</where>
</select>
4.使用<sql>标签实现SQL片段的抽取
就像之前学切点表达式一样,一些被重复使用的SQL片段:select * from user
可以抽取出来:
<sql id="selectUser">select * from user</sql>
然后在需要用到这个片段的地方使用<include>标签直接引入,不需要自己再手动去写
<include refid="selectUser"/>