MySQL中根据if标签实现多条件模糊查询(动态SQL语句)

 if标签

 

 if标签可用在许多类型的sql语句中,我们以查询为例。首先看一个很普通的查询:

Xml代码   收藏代码
  1. <!-- 查询学生list,like姓名 -->  
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
  5. </select>  

 

 

但是此时如果studentName或studentSex为null,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断,增加灵活性。

参数为实体类StudentEntity。将实体类中所有的属性均进行判断,如果不为空则执行判断条件。

Xml代码   收藏代码
  1. <!-- 2 if(判断参数) - 将实体类不为空的属性作为where条件 -->  
  2. <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      WHERE  
  12.     <if test="studentName !=null ">  
  13.         ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.     </if>  
  15.     <if test="studentSex != null and studentSex != '' ">  
  16.         AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.     </if>  
  18.     <if test="studentBirthday != null ">  
  19.         AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.     </if>  
  21.     <if test="classId != null and classId!= '' ">  
  22.         AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.     </if>  
  24.     <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.         AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.     </if>  
  27.     <if test="placeId != null and placeId != '' ">  
  28.         AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.     </if>  
  30.     <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.         AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.     </if>  
  33.     <if test="studentId != null and studentId != '' ">  
  34.         AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.     </if>   
  36. </select>  
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值