trim标签的用法
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
如果state、title和author属性均为null,则生成的SQL语句语法错误
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
- where元素只会在子元素返回任何内容的情况下才插入WHERE子句。如果state、title和author均
为null时,则不会生成where子句 - where标签另外提供功能,就是子句的开头为AND或OR,where元素也会将它们去除。例如state
为null,但是title不为空
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<trim prefix="WHERE" prefixOverrides="AND |OR ">如果trim标签体不为空,则自动在
标签体内容的前部添加前缀WHERE,如果标签体内容以and或者or开头,则自动剔除开头的and或者or。
另外处理尾部的suffix或者suffixOverrides
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</trim>
</select>
choose、when、otherwise类似于java中的开关分支语句
<select id="selectByExample" parameterType="DeptBean"
resultMap="baseMapper">
select <include refid="columns"/> from t_dept
<where>
<choose>
<when test="id != null">
AND id like #{id}
</when>
<when test="deptName != null">
AND dept_name like #{deptName}
</when>
<otherwise>
AND location like '中国%'
</otherwise>
</choose>
</where>
</select>
set标签用于动态生成update语句中的set部分
set元素可以用于动态包含需要更新的列,忽略其它不更新的列
foreach
对集合进行遍历
批量删除操作delete from t_dept WHERE id in( 1 , 2 , 3 , 4 )
<delete id="deleteByIds" parameterType="list">
delete from t_dept
<where>
<foreach collection="list" item="kk" open="id in(" close=")" separator="," nullable="true">
${kk}
</foreach>
</where>
</delete>
批量插入操作 insert into t_dept values (?,?,?) , (?,?,?) , (?,?,?) , (?,?,?) , (?,?,?)
<insert id="insertCollection" parameterType="list">
insert into t_dept
<foreach collection="list" open="values" separator="," item="dd">
(#{dd.id},#{dd.deptName},#{dd.location})
</foreach>
</insert>
select
<select
id="selectPerson"
parameterType="int"
parameterMap="deprecated"
resultType="hashmap"
resultMap="personResultMap"
flushCache="false"
useCache="true"
timeout="10"
fetchSize="256"
statementType="PREPARED"
resultSetType="FORWARD_ONLY">
insert
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
keyColumn=""
useGeneratedKeys=""
timeout="20">
delete
<delete
id="deleteAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
update
<update
id="updateAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">