码迷,mamicode.com
首页 > 数据库 > 详细

mybatis动态sql

时间:2015-11-10 16:30:54      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

mybatis动态sql使用的标签:

1:if  判断

2:where   解决sql语句拼接条件问题

例:

<select id="findUserById" resultType="user">

           select * from user where 

           <where>

           <if test="id != null">

               id=#{id}

           </if>

            and deleteFlag=0;

           </where>

</select>

如果id = null 则sql语句会为: select * from user where and and deleteFlag=0,很明显这个是错误的sql语句。添加where便签变可以解决,如上<where></where>  去掉上面红色部分where

3:trim  处理拼接

2中的问题也可以这样处理

<select id="findUserById" resultType="user">

           <trim prefix="where"  prefixOverrodes="and | or">

           ?select * from user where ?

           <if test="id != null">

               id=#{id}

           </if>

            and deleteFlag=0;

            </trim>

</select>

4: set

<update id="updateUser" parameterType="com.domin.User">

           update user set 

           <set>    

                 <if test="name != null">

               name = #{name},

           </if> 

           </set>

               and deleteFlag = 0;

           </where>

</update>

如果name = null,则sql语句为update user set  and deleteFlag = 0,明显错误。使用<set></set> 替代<set>

也可以是trim处理

5:foreach 循环遍历集合或数组

<select id="selectUser" resultType="domain.domin.User">

  select *

  from user

  where id in

  <foreach item="item" index="index" collection="list"

      open="(" separator="," close=")">

        #{item}

  </foreach>

</select>

对应的sql如下:

select * from user where id in(item1,item2...)    

item1,item2...代表#{item}每次的值

6:choose 相当于java中的swich

格式如下:

  <choose>

    <when>

    语句

    </when>

    <otherwise>

    语句

    </otherwise>

  </choose>

遇到的问题:

<![CDATA[
AND  shelve_at <= #{currentTimeMillis,jdbcType=BIGINT} AND #{currentTimeMillis,jdbcType=BIGINT} < unshelve_at
]]>

//不能写成
<![CDATA[
AND  shelve_at <= #{currentTimeMillis,jdbcType=BIGINT}  < unshelve_at
]]>










mybatis动态sql

标签:

原文地址:http://my.oschina.net/u/2361475/blog/528487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!