---
title: "ibatis中iterate的用法"
author: "ilovejavaforever"
date: "2010-10-20T09:10:54Z"
tags: []
categories: ["企业架构"]
slug: "ibatis-iterate"
draft: false
lastmod: "2010-10-20T09:10:54Z"
id: 789146
url: "https://ilovejavaforever.iteye.com/blog/789146"
---

**版权声明：** 原创作品，允许转载，转载时请务必以超链接形式标明文章 [原始出处](http://sunfish.blog.51cto.com/417500/108315)  、作者信息和本声明。否则将追究法律责任。[http://sunfish.blog.51cto.com/417500/108315](http://sunfish.blog.51cto.com/417500/108315)

PersonDaoImp如下:

  /\**  
    * 删除性别为man,年龄为 11,12 的Person记录  
    \*/  
  public  int  deletePerson(Map&lt;String, Object&gt; map) {  
           
         List&lt;Person&gt; personList =new  ArrayList&lt;Person&gt;();

         Person p1=new  Person(11);  
         person p2=new  Person(12);  
         personList.add(p1);  
         personList.add(p2);

         map.put("personList" , personList );

         map.put("sex" ,'man');  
         return  getSqlMapClientTemplate().delete(  
                                 "person.deletePerson" , map);  
     }

person.xml如下:

&lt;!-- 删除相应的person记录  --&gt;  
  &lt; delete  id =" deletePerson "  parameterClass ="map" &gt;

    delete from 表名 where      sex=#sex#           
        &lt; iterate   prepend ="and "  property =" personList "  open ="("  
          close =")"  conjunction ="or" &gt;  
          age=$personList\[] .age $  
        &lt;/ iterate &gt;    
         
  &lt;/ delete &gt;

输出sql如下:  
delete from 表名 where sex='man' and ( age =11 or  age=12)

当然你也可以这么写:  
person.xml如下:

&lt;!-- 删除相应的person记录  --&gt;  
  &lt; delete  id =" deletePerson "  parameterClass ="map" &gt;

    delete from 表名 where      sex=#sex#     and age in      
        &lt; iterate  property =" personList "  open ="("  
          close =")"  conjunction ="," &gt;  
          $personList\[] .age $  
        &lt;/ iterate &gt;    
         
  &lt;/ delete &gt;

输出sql如下:  
delete from 表名 where sex='man' and  age in ( 11 , 12)

最后Person代码大致如下:

public  class  Person{  
  public  Person(int  age){  
      this.age=age;  
  }  
  /\**  
    * 年龄  
    \*/  
  private  int age;  
  /\**  
    * 性别  
    \*/  
  private  String sex;  
    
   //get/set方法略  
   ...  
 }//end of Person

本文出自 “[sunfish 翻车鱼](http://sunfish.blog.51cto.com/) ” 博客，请务必保留此出处[http://sunfish.blog.51cto.com/417500/108315](http://sunfish.blog.51cto.com/417500/108315)