知识点:
特别注意点{
1. xml 文件需要转义部分字符
如: > >
< ≶
&
&
2.
CDATA 部分由 "
<![CDATA[
" 开始,由 "
]]>
" 结束:
<![CDATA [
这里的特殊符号不需要转义
]]>
}
1.#{} 与${} 的区别
#{} : mybatis 常用获取参数
${} : Ibatis 常用获取参数(不建议使用'${}') #{} = '${}'
妙用: 一些不希望字符串值改变(需要安全校验) 如:
oder by ${paramKey} //paramKey : id
此时 希望 得到id 不是'id'
2. 主键生成 并插入
// 1.没有设置自动生成序列
<insert id="insertAuthor" parameterType="domain.blog.Author">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio},
#{favouriteSection,jdbcType=VARCHAR}
)
</insert>
// 设置了自动生成序列
<insert id="insertAuthor" parameterType="domain.blog.Author" userGeneratedKeys ='true'
keyProperty ="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
order="BEFORE|AFTER" 在insert 前后执行
3. 动态sql
(1) if
<if test=" param != null "></if>
(2)choose (等价if-elseIf-else)
<choose>
<when test=" ">
sql 1
</when>
<when test=" ">
sql 2
</when>
<otherwise>
sql 3
</otherwise>
</choose>
(3) set 更新数据时使用会自动补上set 消除多余逗号
update t_table_name
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
(4) foreach
-- IN 语句使用
`id` IN
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
4 批量更新使用
update table_name
set
<foreach item="item" index='index' collection='list' >
<if test="item.id ">
name=#{item.name} ,
number=#{item.number} ,
...
</if>
</foreach>
where id in
<foreach item="item" index='index' collection='list' open="(" separaor=',' close=')'>
#{item.id}
</foreach>