如何使用In子句和IBatis2中的空Java列表处理SQL语句?

时间:2015-02-16 08:15:24

标签: java ibatis

我用IBatis2创建了以下SQL语句:

SELECT    COUNT(*)         
FROM    myTable
WHERE   myTable.id = 4711
AND     myTable.name = 'Maik'
AND     myTable.employee_id IN            
    <iterate property="employee_ids" open="(" close=")" conjunction=",">                    
        #employee_ids[]#                    
    </iterate>  

现在我遇到了问题,employee_ids可以为null或为空。在这种情况下,SQL语句将崩溃。如何在此SQL语句中阻止空或可空的迭代? &#34; employee_ids&#34;是一个Java&#34; List&#34;。

非常感谢!

2 个答案:

答案 0 :(得分:1)

就像那样:

   SELECT    COUNT(*)         
   FROM    myTable
   WHERE   myTable.id = 4711
   AND     myTable.name = 'Maik'
   AND     myTable.employee_id IN     

   <if test="employee_ids!= null and employee_ids.size()>0">
     <iterate property="employee_ids" open="(" close=")" conjunction=",">                    
    #employee_ids[]#                    
    </iterate>   
   </if> 
   <if test="employee_ids== null or employee_ids.size()==0">  
    <![CDATA[
    ()
    ]]
    >
   </if>   

答案 1 :(得分:1)

对于IBatis 2,您可以使用动态sql isNotEmpty来检查null或空列表。

对于您的情况,请尝试以下操作。

SELECT    COUNT(*)         
FROM    myTable
WHERE   myTable.id = 4711
AND     myTable.name = 'Maik'
<dynamic>
<isNotEmpty prepend="AND" property="employee_ids">
    myTable.employee_id IN            
    <iterate property="employee_ids" open="(" close=")" conjunction=",">                    
        #employee_ids[]#                    
    </iterate>
</isNotEmpty>
</dynamic>