zoukankan      html  css  js  c++  java
  • Mybatis中sql语句中的in查询,一定要判断null的情况

    不严谨的写法,可能会报错:in (),这种情况不符合mysql的语法。

        select from loanwhere LOAN_ID in 

    <foreach item="item" index="id" collection="list" open="(" separator="," close=")">  

         #{item}  


    要么在Mybatis的sql文件中,要么在Java程序中。

     

    sql中的写法

    <select id="findByLoanIds" parameterType="List">

    select *

    from p2p_loan_variation where 1= 1

    <if test="list != null and list.size>0">

    and LOAN_ID in

    <foreach item="item" index="id" collection="list" open="("

    separator="," close=")">

    #{item}

    </foreach>

    </if>

    <if test="list==null or list.size==0">and 1=0</if>

    </select>

    Java中的写法:

      List<LoanVariation> list = null;

         if(ListUtils.isNotEmpty(loadIds){

          list =loanVariationDao.findByLoanIds(loanIds);

       }

      return list;

    如果有多个Java方法调用dao mapper,在sql中写比较省事,毕竟只需要一次“参数检查”。

    上面的写法是针对一个查询条件的,如果有多个查询条件,记得处理条件之间的关系,

    比如 a=1 and b =2 or c=3.

    如果有in条件,最好加上括号,(a=1) and (b =2 ) or ( c in ...)

  • 相关阅读:
    飞入飞出效果
    【JSOI 2008】星球大战 Starwar
    POJ 1094 Sorting It All Out
    POJ 2728 Desert King
    【ZJOI 2008】树的统计 Count
    【SCOI 2009】生日快乐
    POJ 3580 SuperMemo
    POJ 1639 Picnic Planning
    POJ 2976 Dropping Tests
    SPOJ QTREE
  • 原文地址:https://www.cnblogs.com/qitian1/p/6463079.html
Copyright © 2011-2022 走看看