Mybatis 中动态SQL

一 常用用法和标签

1 where 和if标签的使用

使用if 和where标签 通过OGNL表达式判断内容是否为空 如果表达式为true 则框架会自动拼接if语句中的内容,否则则会忽略

   <select id="getUserByEntity" parameterType="int" resultType="com.mybatis.pojo.User">
        select
        <include refid="userAllField"></include>
        from user
        <where>
            <if test="id!=null">
                AND id=#{id}
            </if>
            <if test="name !=null">
                AND name =#{name}
            </if>
            <if test="phone !=null">
                AND phone=#{phone}
            </if>
        </where>
    </select>

2 <choose|when|otherwise> 

<select id="getUserInfo" parameterType="int" resultType="com.mybatis.pojo.User">
        select
        <include refid="userAllField"></include>
        from user where 1=1
        <choose>
            <when test="id!=null">
                AND id=#{id}
            </when>
            <when test="name !=null">
                AND name =#{name}
            </when>
            <otherwise>
                AND phone is not null 
            </otherwise>
        </choose>
    </select>

所有的when标签和otherwise标签是互斥的,任何一个when标签满足条件时,其他标签均视为不成立。

3 <foreach>

<select id="getUserByPhone" parameterType="int" resultType="com.mybatis.pojo.User">
        select
        <include refid="userAllField"></include>
        from user 
        where phone in 
        <foreach item="phone" index="index" collection="phones"
                 open="(" separator="," close=")">
            #{phone}
        </foreach>
    </select>

4 <trim|set>

这两个标签跟where有点类似,用于where子句中因为不同的条件成立时导致AND 或OR关键字多余,或者SET子句中出现多余的逗号问题

<select id="getUserByEntity" parameterType="int" resultType="com.mybatis.pojo.User">
        select * from user 
        <trim prefix="WHERE" prefixOverrides="AND | OR">
            <if test="id !=null">
                id=#{id}
            </if>
            <if test="name !=null">
                AND name =#{name }
            </if>
        </trim>
    </select>

二 SqlSource 与 BoundSql

SqlSource表示Sql和xml文件配置的SQL资源

其有四个实现类:

(1)ProviderSqlSource:用于表述@Select @SelectProvider等注解配置的资源信息。

 (2)DynamicSqlSource:用于描述MapperXML文件中配置的SQL资源信息,包含动态sql

(3)RawSqlSource:xml文件中的信息,不包含动态sql

(4)staticSqlSource:用于描述上述动态sql解析后得到的静态sql资源

BoundSql 用于封装Mapper解析后的SQL语句和参数信息,

三 LanguageDriver  用于将Sql的配置信息转换为SqlSource的对象

四 sqlLNode  用于解析sql节点

public interface SqlNode{

   boolean apply(DynamicContext context)

}

五 #{} 与${} 区别

使用 #{} 参数占位符时,占位符会被替换成? 然后通过PreparedStatement 对象的setXX()方法为参数占位符设置值;

使用${} 内容会直接被替换成参数值。使用 #{} 参数占位符能够避免SQL注入的问题,优先考虑#{}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值