ibatis 3 学习笔记 5
原创 ibatis 3 学习笔记 5 收藏
动态sql语句
可以在xml文件中添加条件配置来动态拼接,调用sql语句
ibatis使用的ONGL表达式有四种元素
if
choose
trim
foreach
if
<select id=”findActiveBlogLike”parameterType=”Blog” resultType=”Blog”>SELECT * FROM BLOG WHERE state = ‘ACTIVE’<if test=”title != null”>AND title like #{title}if><if test=”author != null && author.name != null”>AND title like #{author.name}if>select>choose,when,otherwise
<select id=”findActiveBlogLike”parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test=”title != null”> AND title like #{title} when> <when test=”author != null && author.name != null”> AND title like #{author.name} when> <otherwise> AND featured = 1 otherwise> choose>select>trim,where,set
where标签可以动态加上where关键字:
<select id=”findActiveBlogLike”parameterType=”Blog” 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 && author.name != null”> AND title like #{author.name} if> where>select>这里也可以自定义trim元素来控制where等关键字,下面的trim配置等价于where标签
<trim prefix="WHERE" prefixOverrides="AND |OR ">…trim>
这里trim标签文档上叙述的很模糊,大概意思是如果trim内的字符带有前缀“AND ”或者“OR ”那么去掉trim整段字符前面的where,否则添加where。
来看update语句中:
<update id="updateAuthorIfNecessary"parameterType="domain.blog.Author">update Author<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}update>set标签等价的trim标签配置为
<trim prefix="SET" suffixOverrides=",">…trim>
这里的trim标签原文叙述的很模糊,大概意思是trim中的字符带有后缀,的话那么就去掉trim整段字符前的set,否则添加set
foreach
<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}foreach>select>基本能明白foreach标签的作用了:
item说明了集合内每一个元素的值,并在下面的sql中使用#{item} 来引用这个值
index说明了集合内每一个元素的下标,并在下面的sql中使用#{index} 来引用这个值
collection说明了集合元素的类型
open是指转换后前面添加(
separator表示每个集合元素之间以“,”分隔
close在转换后最后添加)。