ibatis传递多个参数

不知何时,ibatis3改为mybatis3了,听说mybatis3不用再需要自己手动实现DAO的实现类了,Service层可以直接使用DAO接口中的方法。

ibatis3如何传递多个参数有两个方法:一种是使用Map,另一种是使用JavaBean。

sqlXml配置:

<!--  
     使用HashMap传递多个参数   
    parameterType 可以是别名或完全限定名 ,map->java.util.Map,这两个都是可以的  
    -->  
    <select id="selectBlogByMap" parameterType="map" resultType="Blog">  
        SELECT t.ID, t.title, t.content  
          FROM blog t  
         WHERE t.title = #{h_title}  
           AND t.content =#{h_content}  
    </select>  
    <!-- 使用JavaBean传递多个参数 -->  
    <select id="selectBlogByBean" parameterType="Blog" resultType="Blog">  
        SELECT t.ID, t.title, t.content  
          FROM blog t  
         WHERE t.title = #{title}  
           AND t.content =#{content}  
    </select>  

测试代码:

/** 
 * 通过Map传递多个参数 
 */  
@Test  
public void testSelectByMap() {  
    SqlSession session = sqlSessionFactory.openSession();  
    Map<String, Object> param=new HashMap<String, Object>();  
    param.put("h_title", "oracle");  
    param.put("h_content", "使用序列!");  
    Blog blog = (Blog)session.selectOne("cn.enjoylife.BlogMapper.selectBlogByMap",param);  
    session.close();  
    System.out.println("blog title:"+blog.getTitle());  
}  
/** 
 * 通过JavaBean传递多个参数 
 */  
@Test  
public void testSelectByBean() {  
    SqlSession session = sqlSessionFactory.openSession();  
    Blog blog=new Blog();  
    blog.setTitle("oracle");  
    blog.setContent("使用序列!");  
    Blog newBlog = (Blog)session.selectOne("cn.enjoylife.BlogMapper.selectBlogByBean",blog);  
    session.close();  
    System.out.println("new Blog ID:"+newBlog.getId());  
}  

一般情况下,我们用ibatis都是传入一个参数,这个参数可以为一个类,一个字符串,一个整型等等,例如:

<select id="selectpw" parameterClass="String" resultClass="String">
            select pwd from userinfo
            where userid=#userid#
        </select>

在方法体里可以用:password = (String)sqlMapClient.queryForObject("selectpw", userid)得到password。
但是有时候我们却想从前面传入两个或多个参数,这时候怎么办呢?

用Map:

在方法体里:我们把多个参数存放在map里,然后在前面获得它:

Map map = new HashMap();
        map.put("userid", userid);
        map.put("name", name);
cardList = (List)sqlMapClient.queryForList("findByName", map);

在SQL语句中:

<select id="findByName" parameterClass="java.util.Map" resultClass="Card">
            select * from cardinfo where userid=#userid# and name like '$name$'
        </select>

这样就可以将多个参数传过去了。