mybatis中的if-else使用及if嵌套使用

╰+攻爆jí腚メ 2023-07-12 14:29 80阅读 0赞

案例一:if-else

在使用mybatis mapper 动态sql时,不免会出现if-else的使用,但是好像又没有这种语法,提供的是choose标签代替if-else

例如:

  1. select * from t_stu t
  2. <where>
  3. <choose>
  4. <when test="query == 0">
  5. and t.status = 1
  6. </when>
  7. <otherwise>
  8. and t.status NOT IN (9,5)
  9. </otherwise>
  10. </choose>
  11. and t.delete_status = 1
  12. </where>

也可以用多个if判断实现:

  1. select * from t_stu t
  2. <where>
  3. <if test="query == 0">
  4. and t.status = 1
  5. </if>
  6. <if test="query != 0">
  7. and t.status NOT IN (9,5)
  8. </if>
  9. and t.delete_status = 1
  10. </where>

案例二:if嵌套

在实际编码过程中会有一些判断条件会一直重复使用,一直写在if标签中写的代码会特长,而且臃肿

  1. select * from t_stu t
  2. <where>
  3. <if test="query == 0 and type = 1">
  4. and t.type = 'we' and t.delete = 1
  5. </if>
  6. <if test="query == 0 and type = 2">
  7. and t.type = 'wq' and t.delete = 1
  8. </if>
  9. <if test="query == 0 and type = 3">
  10. and t.type = 'wr' and t.delete = 1
  11. </if>
  12. </where>

变现后:

  1. select * from t_stu t
  2. <where>
  3. <if test="query == 0">
  4. <if test="type = 1">
  5. and t.type = 'we'
  6. </if>
  7. <if test="type = 2">
  8. and t.type = 'wq'
  9. </if>
  10. <if test="type = 3">
  11. and t.type = 'wr'
  12. </if>
  13. </if>
  14. and t.delete = 1
  15. </where>

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读

    相关 excelif嵌套使用方法

    if函数是 Excel 中的条件判断函数,它由条件与两个返回结果组成,当条件成立时,返回真,否则返回假。if函数中的条件既可以单条件,也可以是多条件;多条件组合有三种方式,一种