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

动态SQL

时间:2017-09-03 23:37:22      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:font   动态sql   util   user   字符   close   test   处理   null   

If:注意要做不等于空字符串校验

    <select id="findUserList" parameterType="user" resultType="user">
        select * from user 
        where 1=1 
        <if test="id!=null and id!=‘‘">
        and id=#{id}
        </if>
        <if test="username!=null and username!=‘‘">
        and username like ‘%${username}%‘
        </if>
    </select>

Where:<where />可以自动处理第一个and

<select id="findUserList" parameterType="user" resultType="user">
        select * from user 
        <where>
        <if test="id!=null and id!=‘‘">
        and id=#{id}
        </if>
        <if test="username!=null and username!=‘‘">
        and username like ‘%${username}%‘
        </if>
        </where>
    </select>

foreach:向sql传递数组或Listmybatis使用foreach解析

1)通过pojo传递list

技术分享

 

<if test="ids!=null and ids.size>0">
            <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," >
                #{id}
            </foreach>
</if>

 

2)传递单个List

 

<select id="selectUserByList" parameterType="java.util.List" resultType="user">
        select * from user 
        <where>
        <!-- 传递List,List中是pojo -->
        <if test="list!=null">
        <foreach collection="list" item="item" open="and id in("separator=","close=")">
            #{item.id} 
        </foreach>
        </if>
        </where>
    </select>

3)传递单个数组(数组中是pojo

    <select id="selectUserByArray" parameterType="Object[]" resultType="user">
        select * from user 
        <where>
        <!-- 传递数组 -->
        <if test="array!=null">
        <foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">
            #{item.id} 
        </foreach>
        </if>
        </where>
    </select>

 

sql只接收一个数组参数,这时sql解析参数的名称mybatis固定为array,如果数组是通过一个pojo传递到sql则参数的名称为pojo中的属性名。

index:为数组的下标。

item:为数组每个元素的名称,名称随意定义

open:循环开始

close:循环结束

separator:中间分隔输出

 

4)传递单个数组(数组中是字符串类型,如果数组中是简单类型则写为#{item},不用再通过ognl获取对象属性值了

    <select id="selectUserByArray" parameterType="Object[]" resultType="user">
        select * from user 
        <where>
        <!-- 传递数组 -->
        <if test="array!=null">
        <foreach collection="array"index="index"item="item"open="and id in("separator=","close=")">
            #{item} 
        </foreach>
        </if>
        </where>
    </select>

 

Sql片段

 Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的

 

 

动态SQL

标签:font   动态sql   util   user   字符   close   test   处理   null   

原文地址:http://www.cnblogs.com/m2492565210/p/7471463.html

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