0
点赞
收藏
分享

微信扫一扫

Mybatis的动态SQL的搭建

Jonescy 2022-04-16 阅读 46
spring

动态SQL的官方介绍:

动态SQL的if语句:【使用概率比较大】
代码:

<select id="???" parameterType="???" resultType="???">
    select * from user where 1=1
    <if test="id!=0">
     and id=${id}
    </if>
    <if test="username!=null">
        and  username=${username}
    </if>
    <if test="password">
        and password=${password}
    </if>
</select>

动态SQL中的forEach标签

代码:

-- sql的等价代码是: select   * from where id IN(?,?,?)     -->
    <select id="???" parameterType="list" resultType="???">
        select * from user
--               collection属性表示的是传入sql语句的参数是数组还是集合  是集合的话参数的值是list是数组的话参数的值是array,名称需要和上面的拆入参数值保持一直
-- open 属性标识的是开始循环前的代码标识,close表示的结束时候的代码标识  item属性是表示循环的变量  随意写    separator表示是循环出来的数据中间的分隔符
        <where>
            <foreach collection="list"  open="id IN(" close=")" item="id" separator="," >
--             #{id}表示将循环出的值进行读取出来
                #{id}
            </foreach>
        </where>

    </select>

进行SQL语言的抽取:

代码:

 
<!--    sql片段的抽取-->
    <sql id="selectUser">select * from user </sql>
    
    <select id="???" parameterType="???" resultType="???">
-- 片段抽取
        <include refid="selectUser"></include>
        <where>
        <if test="id!=0">
         and id=${id}
        </if>
        <if test="username!=null">
            and  username=${username}
        </if>
        <if test="password">
            and password=${password}
        </if>
        </where>
    </select>
举报

相关推荐

0 条评论