时间:2021-07-01 10:21:17 帮助过:28人阅读
MyBatis中常用动态SQL:
choose when otherwise if trim where foreach
1,<if>元素被用来有条件地嵌入SQL片段,如果测试条件被赋值为true,则相应地SQL片段将会被添加到SQL语句中。
<select id="searchCourses" parameterType="map" resultMap="CourseResult">
            SELECT * FROM COURSES
            WHERE TUTOR_ID= #{tutorId}
            <if test="courseName != null">
                AND NAME LIKE #{courseName}
            </if>
<......>
</select>
2,choose,when 和 otherwise 条件(相当于if ,else if,else)
  select * from test where 1 = 1
  <choose>
        <when test="a!= null">
              and a= #{a}
        </when>
        <when test="b!= null">
              and b= #{b}
        </when>
        <otherwise>
              and c = #{c}
        </otherwise>
  </choose>
3.foreach
  
4.trim
<trim>标签属性:
<where>和<set>标签都可以用trim标签实现,并且底层就是通过TrimSqlNode实现的。
5.where(常用于select语句)
where标签的作用:如果该标签包含的元素中有返回值,就插入一个where;如果where后面的字符是以AND和OR开头的,就讲他们剔除。
  <select id="findUserByWhere" resultType="User">
      SELECT * FROM user
      <where>
        <if test="name != null and name != ‘‘">
            AND name LIKE concat(‘%‘, #{name}, ‘%‘)
        </if>
        <if test="phone !=null and phone !=‘‘">
            OR phone=#{phone}
        </if>
      </where>
  </select>
6.set(常用于update语句)
标签的作用:如果该标签包含的元素中有返回值,就插入一个set;如果set后面的字符串是以逗号结尾的,就将这个逗号剔除。
  <update id="updateUser">
        UPDATE user
      <set>
            <if test="user.email != null and user.email != ‘‘">email=#{user.email},</if>
            <if test="user.phone != null and user.phone != ‘‘">phone=#{user.phone},</if>
      </set>
        WHERE uid=#{user.uid}
  </update>
Mybatis动态sql技术
标签:语句 sele email mail sel 属性 from 返回值 字符