動態 SQL 元素和 JSTL 或基於類似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時間了解。
MyBatis 3 大大精簡了元素種類,現在只需學習原來一半的元素便可。MyBatis 采用功能強大的基於 OGNL 的表達式來淘汰其它大部分元素。
SQL標簽(if,choose,where,trim,foreach)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zhiyou100.hhz.dao.UsersDao"> <!-- 動態sql片段 --> <sql id="userscolumn">id,name,sex,age,created</sql> <select id="selectByWhere" parameterType="int" resultType="com.zhiyou100.hhz.bean.Users"> select <include refid="userscolumn"/> from users <!-- where 可以在第一個判斷成功的語句前加where 且去除and --> <where> <if test="name!=null and name!=''"> and name=#{name} </if> <if test="sex!=null and sex!=''"> and sex=#{sex} </if> <if test="age>0"> and age=#{age} </if> </where> </select> <update id="updateByWhere"> update users <!-- set可以在第一個判斷成功的語句前加set 且去除, --> <set> <if test="name!=null and name!=''"> name=#{name}, </if> <if test="sex!=null and sex!=''"> sex=#{sex}, </if> <if test="age>0"> age=#{age}, </if> <if test="created!=null and created!=''"> created=#{created} </if> </set> where id=#{id} </update> <select id="selectByWhere2" resultType="com.zhiyou100.hhz.bean.Users"> select <include refid="userscolumn"/> from users <!-- trim可以代替where和set 做到類似的效果 prefix:添加前綴 prefixOverrides:去除前綴 suffix:添加后綴 suffixOverrides:去除后綴 --> <trim prefix="where" prefixOverrides="and"> <if test="name!=null and name!=''"> and name=#{name} </if> <if test="sex!=null and sex!=''"> and sex=#{sex} </if> <if test="age>0"> and age=#{age} </if> </trim> </select> <!-- 循環遍歷數組 collection:集合 open:前綴 close:后綴 separator:每次遍歷的間隔 item:集合命名 --> <delete id="deleteById"> delete from users where id in <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach> </delete> <select id="selectById" resultType="com.zhiyou100.hhz.bean.Users"> select <include refid="userscolumn"/>from users <where> <!-- choose+when+otherwise類似java中的switch+case+default --> <choose> <when test="name!=null and name!=''"> name=#{name} </when> <when test="sex!=null and sex!=''"> sex=#{sex} </when> <when test="age>0"> age=#{age} </when> <otherwise> created=#{created} </otherwise> </choose> </where> </select> </mapper>