MyBatis运用心得(3)
2.Dynamic SQL
动态sql是MyBaits的优点之一,在以往的IBatis就有动态sql,在此只是简要概述
在MyBatis中,sql的定义基于2中方式,一种是传统的XML文件,一种是Java的Mapper类生成
1)基于Mapper的动态SQL:
此部分在"MyBatis运用心得(2)"中已经叙述,主要是利用SelectBuilder和SqlBuilder,还是十分容易理解的。
2)基于XML文件的动态SQL:
主要是利用一些标签:<if>,<where>,<when>,<choose>,<otherwise>,<set>,<trim>,<foreach>
这些标签有一些与jstl比较相近,如<when>,<choose>,<otherwise>,<if>,<foreach>等。
<where>的作用主要是在一个where语句中如果有多个<if>,有可能会多出and和or连接符,如:
where<if test="name != null"> name = #{name}</if><if test="id != null"> and id = #{id}</if><where> <if test="name != null"> name = #{name} </if> <if test="id != null"> and id = #{id} </if></where>update A<set> <if test="name != null"> name = #{name}, </if> <if test="id != null"> id= #{id} </if></set><where> <choose> <when test="@com.test.OgnlHelper@hasSpecialChar(name)"> and name like '%'||#{name}||'%' escape '\' </when> <otherwise> and name like '%'||#{name}||'%' </otherwise> </choose></where>