视频地址:http://edu.51cto.com/sd/be679

动态Sql是Mybatis的核心,就是对我们的sql语句进行灵活的操作,他可以通过表达式,对sql语句进行判断,然后对其进行灵活的拼接和组装。可以简单的说成Mybatis中可以动态去的判断需不需要某些东西。

  动态Sql主要有以下类型:

    if

    choose,when,otherwise

    trim,where,set

    foreach

  这里主要介绍几个常见的where  if  foreach,直接贴代码了

    1.where 这里的where有一个好处就是在拼接成功的时候,会自动去掉第一个and

    2.if 这里的if和java基础中的if用法是一样,在这里的用法就是当条件成立的时候,就会把sql语句拼接上去,不成立的时候就会把if里面的sql语句忽略

    3.if可以重复并且嵌套使用

    4.这里的student.name是包装类的写法

  foreach的用法:把sid在4,5,6,7中的学生找出来 SELECT * FROM t_student WHERE sid in (4,5,6,7);

<!-- 测试foreach代码 -->
<sql id="forEache">
    <if test="sid_s!=null">
                <!-- 
                    collection:指定你输入的集合的属性
                    item:每次遍历的对象名(别名)
                    open:开始遍历的时候拼接的字符串
                    close:结束遍历的时候要拼接的字符串
                    separator:遍历的对象中间要拼接的字符串
                    SELECT * FROM t_student WHERE sid in (4,5,6,7);
                 -->
                <foreach collection="sid_s" item="sid" open="and sid in (" close=")" separator=",">
                    #{sid}
                </foreach>
            </if> 
</sql>

  Sql片段:(提高配置文件中Sql代码的重用性)

    Sql片段的写法:

<!-- 
    id:这个是唯一标识sql代码片段
    经验 :    基于单表写的sql代码重用性比较高】
        :    就是在sql代码里不要出现where
 -->
<sql id="query_list">
    <if test="student!=null and student!=''">
            <if test="student.name!=null and student.name!=''">
                and name=#{student.name}
            </if>
            <if test="student.sex!=null and student.sex!=''">
                and sex=#{student.sex}
            </if> 
        </if>
</sql>

    Sql片段的引用:(可以引用其他配置文件的sql片段:命名空间.sql片段的Id)

<!-- 拼接成功的时候,这个where会自动去掉第一个 and -->
    <where>
        <include refid="query_list"></include>    
    </where>