MyBatis where标签语句

当 where 中的条件使用的 if 标签较多时,这样的组合可能会导致错误。当 java 代码按如下方法调用时:

@Test  
public void select_test_where() {  
    User user = new User();  
    user.setUsername(null);  
    user.setSex(1);  
    List<User> userList = this.dynamicSqlMapper.getUsertList_where(user);  
    for (User u : userList ) {  
        System.out.println(u.toString());  
    }  
}  

如果上面例子,参数 username 为 null,将不会进行列 username 的判断,则会直接导“WHERE AND”关键字多余的错误 SQL。

这时可以使用 where 动态语句来解决。“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或OR 开头的,则它会剔除掉。

上面例子修改为:

<select id="getUserList_whereIf" resultMap="resultMap_User" parameterType="com.yiibai.pojo.User">  
    SELECT u.user_id,  
           u.username,  
           u.sex,  
           u.birthday 
      FROM User u
    <where>  
        <if test="username !=null ">  
            u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="sex != null and sex != '' ">  
            AND u.sex = #{sex, jdbcType=INTEGER}  
        </if>  
        <if test="birthday != null ">  
            AND u.birthday = #{birthday, jdbcType=DATE}  
        </if> 
    </where>    
</select>  

where 主要是用来简化 sql 语句中 where 条件判断,自动地处理 AND/OR 条件。

<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
        select * from t_blog 
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                and owner = #{owner}
            </if>
        </where>
    </select>

where 元素的作用是会在写入 where 元素的地方输出一个 where,另外一个好处是你不需要考虑 where 元素里面的条件输出是什么样子的,MyBatis 会智能的帮处理,如果所有的条件都不满足那么 MyBatis 就会查出所有的记录,如果输出后是 and 开头的,MyBatis 会把第一个and忽略,当然如果是 or 开头的,MyBatis 也会把它忽略;此外,在 where 元素中你不需要考虑空格的问题,MyBatis 会智能的帮你加上。像上述例子中,如果 title=null, 而 content != null,那么输出的整个语句会是 select * from t_blog where content = #{content},而不是 select * from t_blog where and content = #{content},因为 MyBatis 会自动地把首个 and / or 给忽略。

 

转载于:https://www.cnblogs.com/borter/p/9608610.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值