IBATIS3的一些用法记录[整理]

来源:互联网 发布:淘宝客服如何设置 编辑:程序博客网 时间:2024/04/29 13:14

动态sql语句

可以在xml配置文件中添加条件配置来动态拼接,调用sql语句,ibatis使用的ONGL表达式有四种元素 
if ,choose ,trim ,foreach

一、if

 <select id="user_list" parameterType="java.util.HashMap" resultType="test.date.user">  select * from tb_common_keywords  <where>   <if test="id!=null">      and id=#{id}   </if>   <if test="createTime!=null">      and createtime=#{createTime}   </if>  </where>  order by createtime desc </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 P WHERE ID in<foreach item="item" index="index" collection="list" open="(" separator="," close=")">#{item}</foreach></select>

item说明了集合内每一个元素的值,并在下面的sql中使用#{item} 来引用这个值 
index说明了集合内每一个元素的下标,并在下面的sql中使用#{index} 来引用这个值 
collection说明了集合元素的类型 
open是指转换后前面添加( 
separator表示每个集合元素之间以“,”分隔 
close在转换后最后添加)。

原创粉丝点击