验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Mybatis中where标签与if标签怎么结合使用

阅读:963 来源:乙速云 作者:代码code

Mybatis中where标签与if标签怎么结合使用

使用标签

select筛选出视图对象的参数,用于给前端返回页面参数使用。

	
        select file_id,
               uuid,
               file_name,
               file_url,
               status,
               create_time,
               update_time
        from file
    

以下代码格式是正确,我们先观察下and或者or的位置。

    
        
        
            
                and file_name like concat('%', #{fileName}, '%')
            
            
                and status = #{status}
            
            
                and create_time between #{params.beginCreateTime} and #{params.endCreateTime}
            
        
    

再看一下错误的写法;

    
        
        
            
                file_name like concat('%', #{fileName}, '%') and
            
            
                status = #{status} and 
            
            
                create_time between #{params.beginCreateTime} and #{params.endCreateTime}
            
        
    

这时候运行该代码,当beginCreateTimeendCreateTime为空时,我们会发现报错SQL执行异常,原因是where多了一个and

总结

标签判断失败后, 标签关键字可以自动去除掉库表字段赋值前面的and,不会去掉语句后面的and关键字,即 标签只会去掉 标签语句中的最开始的and关键字。所以上面的写法(and写在后面)是不符合mybatis规范的。

不使用标签

当不使用标签时,正确的写法可以参考以下代码:


        
        where 1=1 
        
            and file_name like concat('%', #{fileName}, '%')
        
        
            and status = #{status}
        
        
            and create_time between #{params.beginCreateTime} and #{params.endCreateTime}
        
    

此时我们发现and是写在前面的,同时增加了1=1条件。

如果我们去掉1=1条件,同时去掉第一个标签的and


        
        where 
        
            file_name like concat('%', #{fileName}, '%')
        
        
            and status = #{status}
        
        
            and create_time between #{params.beginCreateTime} and #{params.endCreateTime}
        
    

这种情况下,当fileName为空时,sql语句中会出现where and这种错误的语法,最终导致sql执行异常。所以正确的代码中,使用1=1条件,当fileName为空时,sql语句就会变成where 1=1 ,后面接不接and都能正确执行。

在不使用标签的情况下,and写在后面,在where条件最后增加1=1判断,原理和上面一样,这里就不再赘述了。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>