动态SQL 语句

动态SQL 语句:

基于OGNL表达式

完成多条件查询等逻辑实现

用于实现动态SQL的元素主要有

if

trim

where

set

choose(when、otherwise)

foreach

 

trim 属性

prefix

suffix

prefixOverrides

suffixOverrides

更灵活地去除多余关键字 替代where和set

 

if+trim 使用if+trim替代if+set进行更新用户表数据,效果一样

<update id ="modify" parameterType="User">
update smbms_user
<trim prefix="set" suffixOverrides="," suffix="where id = #{id}">    
    <if test="userCode != null">userCode = #{userCode},</if>
    <if test="userName!= null">userCode = #{userName },</if>
    <if test="userPassword!= null">userPassword=#{userPassword },</if>
</trim>
</update>

foreach  迭代一个集合,通常用于in条件

属性

item

index

collection:必须指定

list

array

map-key

open

separator

close

 

choose(when、otherwise)

<choose>
    <when test ="条件1"> …</when>
    <when test ="条件2"> …</when>
    <when test ="条件3"> …</when><otherwise>…</otherwise>
</choose>    

 

引入依赖

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
     <build>
            <resources>
                <resource>
                    <directory>${basedir}/src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
            </resources>
        </build>

 

总结:

if+set     if-where     if+trim    choose(when、otherwise)

foreach item idex Collection list array map open separator close

 

posted @ 2020-11-11 21:19  Kc_blog  阅读(199)  评论(2编辑  收藏  举报