标签:mode varchar type 联合 test lib div table date
MyBatis中动态SQL包括元素:
元素 | 作用 | 备注 |
---|---|---|
if | 判断语句 | 单条件分支判断 |
choose(when、otherwise) | 相当于Java中的case when语句 | 多条件分支判断 |
trim(where、set) | 辅助元素 | 用于处理SQL拼接问题 |
foreach | 循环语句 | 用于in语句等列举条件 |
if元素是最常用的判断语句,常与test属性联合使用。
<resultMap id="baseResultMap" type="com.libing.helloworld.model.Role"> <id property="id" column="id" /> <result property="roleName" column="role_name" /> </resultMap>
<select id="findBySearchText" resultMap="baseResultMap"> SELECT id, role_name FROM role WHERE 1 = 1 <if test="searchText != null and searchText != ‘‘"> AND role_name LIKE CONCAT(‘%‘, #{searchText,jdbcType=VARCHAR}, ‘%‘) </if> ORDER BY id ASC </select>
<select id="findBySearchText" resultMap="baseResultMap"> SELECT id, role_name FROM role <where> <if test="id > 0"> id >= #{id} </if> <if test="searchText != null and searchText != ‘‘"> AND role_name LIKE CONCAT(CONCAT(‘%‘,#{searchText,jdbcType=VARCHAR}),‘%‘) </if> </where> ORDER BY id ASC </select>
MyBatis中where标签会判断如果所包含的标签中有返回值,则插入一个‘where’。此外,如果标签返回的内容是以AND或OR开头,则自动删除开头的AND或OR。
<update id="update" parameterType="com.libing.helloworld.model.Role"> UPDATE role <set> <if test="roleName != null and roleName != ‘‘"> role_name = #{roleName}, </if> <if test="remark != null and remark != ‘‘"> remark LIKE CONCAT(‘%‘, #{remark, jdbcType=VARCHAR}, ‘%‘) </if> </set> WHERE id = #{id} </update>
上面形式,当ramark=null时,动态SQL语句会由于多出一个“,”而错误。
<select id="findByCondition" resultMap="baseResultMap"> SELECT id, role_name FROM role <where> <choose> <when test="id > 0"> id >= #{id} </when> <otherwise> AND role_name LIKE CONCAT(‘%‘, #{roleName, jdbcType=VARCHAR}, ‘%‘) </otherwise> </choose> </where> ORDER BY id ASC </select>
<select id="findByCondition" resultMap="baseResultMap"> SELECT id, role_name FROM role <trim prefix="where" prefixOverrides="AND | OR"> <if test="id > 0"> id >= #{id} </if> <if test="roleName != null and roleName != ‘‘"> AND role_name = LIKE CONCAT(‘%‘, #{roleName, jdbcType=VARCHAR}, ‘%‘) </if> </trim> ORDER BY id ASC </select>
<update id="update" parameterType="com.libing.helloworld.model.Role"> UPDATE role <trim prefix="set" suffixOverrides=","> <if test="roleName != null and roleName != ‘‘"> role_name = #{roleName}, </if> <if test="remark != null and remark != ‘‘"> remark LIKE CONCAT(‘%‘, #{remark, jdbcType=VARCHAR}, ‘%‘) </if> </trim> WHERE id = #{id} </update>
标签:mode varchar type 联合 test lib div table date
原文地址:http://www.cnblogs.com/libingql/p/7475227.html