概述: 有些时候业务逻辑复杂时,我们的sql是动态变化的,此时我们就需要用到动态sql
1. 动态sql之 标签
我们根据实体类的不同取值,使用不同的sql语句进行查询。比如id如果不为空时可以根据id查询,如果username不同空时还要加入用户作为条件。这种情况在我们的多条件组合查询中经常会碰到
注意:标签的test属性中写的是对象属性名,如果是包装类的对象要使用ognl表达式的写法。另外注意 where 1=1的作用
2.动态sql之标签
为了简化上面的where 1=1 的条件拼装,我们可以采用标签来简化开发修改UserDao.xml映射文件如下
可以自动处理第一个and,多出来的and会自动去掉
3.动态标签之 标签
方式一
方式二
方式三
4.sql片段
sql中可将重复的slq提取出来,使用时用include引用即可,最终达到sql重用的目的。
我们线到UserDao,xml文件中使用标签定义出公共部分,如下:
<sql id="selectUserTable">
select id id_. username username_, birthday birthday_,sex sex_, address address_ from user
</sql>
然后在UserDao.xml文件中用标签引用上面的id
其中标签的refid属性的值就是 标签定义id的取值。
注意:如果引用其他mapper.xml的sql片段则在引用时需要加上namespace,如下:
<select id= "findByRange" parameterType="queryvo" resultMap="userResultMap">
<include refid="selectUserTable"></include>
<where>
<if test="ids !=null and ids.size>0">
<foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>