如何进行ibatis动态多条件组合查询以及模糊查询

来源:互联网 发布:今日eia数据 编辑:程序博客网 时间:2024/06/06 17:50
这几天在学习使用IBATIS突然要使用模糊查询,以及动态多个条件查询,按照自己的想法试了很久,都没解决这个问题.
首先是模糊查询的问题,开始时我使用如下条件:select * from user where name like '%#value#%'. 可是怎么也不行,好像还报错了.后来在网上找到了解决方法,就是使用$来代替#号.

1>写成: like '%$value$%' 就可以了,<!-- 模糊查询不能用#,#是用prepareStatement的?插入参数,$是文本替换 -->,

2>同时还找到另一个方法,但是那个方法我试了很久,就是不行,方法为: like '%' || #value# || '%'  , 查询出来的结果居然是全部.后来在网上有人说,这个写法是oracle的写法,

3>如果是mysql,则应该写成: name like CONCAT('%',#value:VARCHAR#,'%')  ,不过我没试用过,反正有一个方法成功就可以了.

第一个方法我试用成功,后面的也就没试过,有兴趣的朋友可以试试


第二个大问题就是多条件组合查询,开始时,我也在想这个问题,总不能为每一个查询都写一个SQL配制吧,这样太........后来参考一些文档,发现,原来IBATIS里提供了动态映射.示例如下:

 <!--在ibatis中使用安全的拼接语句,动态查询ibatis比JDBC的优势之一,安全高效说明文字在注释中-->  <select id="selectAllProducts" parameterClass="Product" resultMap="ProductResult">    select id,note from Product       <dynamic prepend="WHERE">       <!-- isNotNull判断参数是否存在,Integer类型 -->            <isNotNull property="id">                <!-- isGreaterThan判断参数是否大于compareValue,isGreaterEquals是大于等于 -->                <isGreaterThan prepend=" and " property="id" compareValue="0">                id = #id#                </isGreaterThan>            </isNotNull>            <!-- isNotEmpty判断字串不为空,isEmpty可以判断字串为空 -->            <isNotEmpty prepend=" and " property="note">            <!-- 模糊查询不能用#,#在是用prepareStatement的?插入参数,$是文本替换 -->            note like '%$note$%'            </isNotEmpty>        </dynamic>  </select>
用Map传参数

 <select id="selectAllProducts" parameterClass="java.util.HashMap" resultMap="ProductResult">    select id,note from Product       <dynamic prepend="WHERE">       <!-- isPropertyAvailable判断属性是否有效 -->          <isPropertyAvailable property="id">            <isNotNull property="id">                <!-- isLessThan判断参数是否小于compareValue,isLessEquals是小于等于 -->                <isLessThan prepend=" and " property="id" compareValue="10">                id = #id#                </isLessThan>            </isNotNull>          </isPropertyAvailable>        </dynamic>  </select>

几个常用属性:


属性关键字

含义

<isEqual>

如果参数相等于值则查询条件有效。

<isNotEqual>

如果参数不等于值则查询条件有效。

<isGreaterThan>

如果参数大于值则查询条件有效。

<isGreaterEqual>

如果参数等于值则查询条件有效。

<isLessEqual>

如果参数小于值则查询条件有效。如下所示:

<isLessEqual prepend = ”AND” property = ”age” compareValue = ”18” >

ADOLESCENT = ‘TRUE’

</isLessEqual>

<isPropertyAvailable>

如果参数有使用则查询条件有效。

<isNotPropertyAvailable>

如果参数没有使用则查询条件有效。

<isNull>

如果参数为NULL则查询条件有效。

<isNotNull>

如果参数不为NULL则查询条件有效。

<isEmpty>

如果参数为空则查询条件有效。

<isNotEmpty>

如果参数不为空则查询条件有效。参数的数据类型为CollectionString 时参数不为NULL或“”。如下所示:

<isNotEmpty prepend=”AND” property=”firstName” >

FIRST_NAME=#firstName#

</isNotEmpty>

<isParameterPresent>

如果参数类不为NULL则查询条件有效。

<isNotParameterPresent>

Checks to see if the parameter object is not present (null). Example Usage:

<isNotParameterPresent prepend=”AND”>

EMPLOYEE_TYPE = ‘DEFAULT’

</isNotParameterPresent>