MyBatis实现根据输入值是否为空进行动态组合查询条件
(2013-05-29 15:41:57)分类: ORM |
例:简单的一个查询
<!-- 查询学生list,like姓名
-->
<select
id="getStudentListLikeName" parameterType="StudentEntity"
resultMap="studentResultMap">
WHERE ST.STUDENT_NAME LIKE
CONCAT(CONCAT('%', #{studentName}),'%')
</select>
但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。
修改为:
<!-- 查询学生list,like姓名
-->
<select id="
getStudentListLikeName " parameterType="StudentEntity"
resultMap="studentResultMap">
</select>
完整版:
<!--
查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->
<select
id="getStudentListWhereEntity" parameterType="StudentEntity"
resultMap="studentResultMap">
</select>
当if标签较多时,这样的组合可能会导致错误。
例如:
<!-- 查询学生list,like姓名,=性别
-->
<select
id="getStudentListWhere" parameterType="StudentEntity"
resultMap="studentResultMap">
</select>
中,参数studentName为null或’’,则或导致此sql组合成“WHERE
AND”之类的关键字多余的错误SQL。
<!-- 查询学生list,like姓名,=性别
-->
<select
id="getStudentListWhere" parameterType="StudentEntity"
resultMap="studentResultMap">
</select>
详见http://blog.csdn.net/ask_rent/article/details/6320326