mybatis同一个搜索框对多个字段进行模糊查询

来源:互联网 发布:谷歌人工智能失控 编辑:程序博客网 时间:2024/06/08 07:02

需求:一个搜索框同时对userId和title进行模糊查询。


第一次:


   <where>      <if test="disId!=null and disId != '' " >         and DIS_ID = #{disId}      </if>      <if test="category!=null" >         and CATEGORY = #{category}      </if>      <if test="userId!=null" >         and USER_ID like CONCAT('%',#{userId},'%' )         </if>      <if test="userType!=null" >         and USER_TYPE = #{userType}      </if>      <if test="title!=null" >         and TITLE like CONCAT('%',#{title},'%' )         </if>    </where>
![日志里的SQL是这样的](http://img.blog.csdn.net/20160707230448959)这种方式查询时,日志里的SQL如上所示,会导致对2个字段进行AND查询,只有都具有相同关键字时才可以被查出来。*

第二次:

*

     <trim prefix="where" prefixOverrides="and \ or">      <if test="disId!=null and disId != '' " >         and DIS_ID = #{disId}      </if>      <if test="category!=null" >         and CATEGORY = #{category}      </if>      <if test="userId!=null" >         and USER_ID like CONCAT('%',#{userId},'%' )         </if>      <if test="userType!=null" >         and USER_TYPE = #{userType}      </if>      <if test="title!=null" >         and TITLE like CONCAT('%',#{title},'%' )         </if>      </trim>  </select>

这里写图片描述在日志中会出现如上图所示的错误,很明显,userId字段前多了“and”,TITLE前应该为“or”。

第三次:

`from QUESTION     <trim prefix="where" prefixOverrides="and \ or">      <if test="disId!=null and disId != '' " >          DIS_ID = #{disId}      </if>      <if test="category!=null" >          CATEGORY = #{category}      </if>      <if test="userId!=null" >         USER_ID like CONCAT('%',#{userId},'%' )         </if>      <if test="userType!=null" >          USER_TYPE = #{userType}      </if>      <if test="title!=null" >        or TITLE like CONCAT('%',#{title},'%' )         </if>      </trim>  </select>

trim标签中不要条件字段,只在 第一个以后的字段前加“or”即可。
好了!

1 0
原创粉丝点击