码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis对入参对象的属性空判断

时间:2016-01-08 23:39:19      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

 

 
<!-- 查询学生list,like姓名 -->  
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST    
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT(‘%‘, #{studentName}),‘%‘)   
</select>  
 
但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。
修改为:
 
<!-- 查询学生list,like姓名 -->  
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
    <if test="studentName!=null and studentName!=‘‘ ">  
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT(‘%‘, #{studentName}),‘%‘)   
    </if>  
</select>
 
完整版:
 
<!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->  
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
    <where>  
        <if test="studentName!=null and studentName!=‘‘ ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT(‘%‘, #{studentName}),‘%‘)   
        </if>  
        <if test="studentSex!= null and studentSex!= ‘‘ ">  
            AND ST.STUDENT_SEX = #{studentSex}   
        </if>  
        <if test="studentBirthday!=null">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday}   
        </if>  
        <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!=‘‘ ">  
            AND ST.CLASS_ID = #{classEntity.classID}   
        </if>  
    </where>  
</select>
 
当if标签较多时,这样的组合可能会导致错误。
例如:
<!-- 查询学生list,like姓名,=性别 -->  
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
        WHERE   
        <if test="studentName!=null and studentName!=‘‘ ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT(‘%‘, #{studentName}),‘%‘)   
        </if>  
        <if test="studentSex!= null and studentSex!= ‘‘ ">  
            AND ST.STUDENT_SEX = #{studentSex}   
        </if>  
</select>
中,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
 
 这时可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
 
<!-- 查询学生list,like姓名,=性别 -->  
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
    <where>  
        <if test="studentName!=null and studentName!=‘‘ ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT(‘%‘, #{studentName}),‘%‘)   
        </if>  
        <if test="studentSex!= null and studentSex!= ‘‘ ">  
            AND ST.STUDENT_SEX = #{studentSex}   
        </if>  
    </where>  
</select> 
 
详见http://blog.csdn.net/ask_rent/article/details/6320326

MyBatis对入参对象的属性空判断

标签:

原文地址:http://www.cnblogs.com/zengda/p/5115194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!