巧妙mybatis避免Where 空条件的尴尬

2022-07-27,,

我就废话不多说了,大家还是直接看代码吧~

<select id="findactivebloglike" resulttype="blog">
 select * from blog
 where
 <if test="state != null">
 state = #{state}
 </if> 
</select>

如果state参数为空时,最终生成sql语句为

select * from blog

where

执行会出错,当然,你可以在where 后加一个1=1,改成

<select id="findactivebloglike" resulttype="blog">
 select * from blog
 where 1=1
 <if test="state != null">
 and state = #{state}
 </if> 
</select>

但是这个做法不太“环保”(毕竟引入了一个垃圾条件),其实只要改成<where>...</where>即可

<select id="findactivebloglike" resulttype="blog">
 select * from blog
 <where>
  <if test="state != null">
   and state = #{state}
  </if>
 </where> 
</select>

补充知识:mybatis @select注解中当参数为空则不添加该参数的判断

如下所示:

@select("select * from "+depttable+" ")

list<dept> selectalldept();

在mybatis中不用xml文件的形式,selectdept方法执行的就是上面的sql语句,如果是遇到动态的语句就需要用到下面的形式。

1.用provider去实现sql拼接:

@selectprovider(type=deptdynasqlprovider.class,method="count")
 integer count(map<string, object> params);
//deptdynasqlprovider.class 类中的方法
public string count(map<string, object> params){
return new sql(){{select("count(*)");from(depttable);if(params.get("dept") != null){dept dept = (dept) params.get("dept");if(dept.getname() != null && !dept.getname().equals("")){where(" name like concat ('%',#{dept.name},'%') ");}}}}.tostring();}

2.还有一种方式是用script标签包围,像xml语法一样书写

@select({"<script>",
 "select * from tbl_order",
 "where 1=1",
 "<when test='title!=null'>",
 "and mydate = #{mydate}",
 "</when>",
 "</script>"})

注意:方式1有个隐患就是当传入参数为空的时候,可能会造成全表查询。

复杂sql用方式2会比较灵活(当然,并不建议写复杂sql),而且可以抽象成通用的基类,使每个dao都可以通过这个基类实现基本的通用查询,原理类似spring jdbc template。

以上这篇巧妙mybatis避免where 空条件的尴尬就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《巧妙mybatis避免Where 空条件的尴尬.doc》

下载本文的Word格式文档,以方便收藏与打印。