---
title: "ibatis 的多条件查询"
author: "falchion"
date: "2009-12-02T16:48:45Z"
tags: []
slug: "ibatis"
draft: false
lastmod: "2009-12-02T16:48:45Z"
id: 539344
url: "https://falchion.iteye.com/blog/539344"
---

ibatis自带的入门例子中，查询条件只有一个。多数情况下，查询条件都是多个的。如果要实现多条件查询，如何实现？  
百度了一下，有以下解决方案：  
1，在java代码中使用字符串拼接  
映射文件中这样写：

view plaincopy to clipboardprint?  
&lt;select id="getBrno" parameterClass="java.lang.String" resultMap="bctlResult"&gt;     
    select brno,brname from bctl where $sql$     
&lt;/select&gt;   
&lt;select id="getBrno" parameterClass="java.lang.String" resultMap="bctlResult"&gt;  
 select brno,brname from bctl where $sql$  
&lt;/select&gt;

然后再java文件中拼写出SQL的条件语句： 

view plaincopy to clipboardprint?  
String sql= " brno like"+ b +"and pigday" = p；// b和p都是变量。   
String sql= " brno like"+ b +"and pigday" = p；// b和p都是变量。

再在方法中调用传递进去：

view plaincopy to clipboardprint?  
brList = sqlMap.queryForList("CR.getBrno", sql);    
brList = sqlMap.queryForList("CR.getBrno", sql); 

这是一种方法，很明显这种方法有一种弊端，就是sql语句需要写在java源文件中。如果需要更改查询条件，就不得不修改java文件，再重新编译。这与ibatis的本意有些违背。  
因此本人没有测试过以上方法是否可行。

2，直接在映射文件中配置参数  
映射文件这样写：

view plaincopy to clipboardprint?  
&lt;!-- 多条件查询--&gt;   
&lt;parameterMap   id="myParam"   class="java.util.HashMap"&gt;       
  &lt;parameter   property="id"/&gt;       
  &lt;parameter   property="name"/&gt;       
&lt;/parameterMap&gt;       
&lt;select   id="multConQuery" parameterMap="myParam" resultClass="Department"&gt;       
    select * from department where id = ? and name = ?         
&lt;/select&gt;    
&lt;!-- 多条件查询--&gt;  
&lt;parameterMap   id="myParam"   class="java.util.HashMap"&gt;    
  &lt;parameter   property="id"/&gt;    
  &lt;parameter   property="name"/&gt;    
&lt;/parameterMap&gt;    
&lt;select   id="multConQuery" parameterMap="myParam" resultClass="Department"&gt;    
    select * from department where id = ? and name = ?      
&lt;/select&gt; 

java文件中这样调用：

view plaincopy to clipboardprint?  
public Department queryDepartmentByIdAndName(int id,String name)    
{    
    Department dept = new Department();    
    try   
    {    
        sqlMapClient.startTransaction();    
        HashMap hmParam = new HashMap();    
        hmParam.put("id",id);    
        hmParam.put("name",name);    
        sqlMapClient.queryForObject("multConQuery",hmParam,dept);    
        sqlMapClient.commitTransaction();    
    }    
    catch(Exception e)    
    {    
        e.printStackTrace();    
    }    
    return dept;    
 } 

 

3、动态查询方法

[详细](http://www.busfly.cn/post/ibatis-oracle-mysql-like.html)