您的位置:首页 > 其它

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

2013-02-08 10:16 706 查看
这几天在学习使用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>

如果参数不为空则查询条件有效。参数的数据类型为Collection、String 时参数不为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>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Mybatis