天天看點

MyBatis傳多個參數的幾種方式1. 傳入對象類型2.用 Map 封裝傳遞3.多個參數類型一樣的情況,可以直接傳入4.多個參數的類型不同時

MyBatis傳多個參數的幾種方式

  • 1. 傳入對象類型
  • 2.用 Map 封裝傳遞
  • 3.多個參數類型一樣的情況,可以直接傳入
  • 4.多個參數的類型不同時

1. 傳入對象類型

在傳參的時候傳遞一個對象類型,自然在擷取的時候可以擷取這個對象的所有屬性, 是以對于傳遞多個參數 , 可以采用把多個屬性封裝到一個對象中的方法實作 . 列出一個例子 :

建立一個 PageBean 類

public class PageBean {
    private int page;
    private int pageSize;

    public int getPage() { return page;}
    public void setPage(int page) {this.page = page;}
    public int getPageSize() {return pageSize; }
    public void setPageSize(int pageSize) {this.pageSize = pageSize;}
}
           

在 …Mapper.java 中編寫方法

在 …Mapper.xml 中編寫查詢語句

<select id="selectByPage_store" resultMap="BaseResultMap" parameterType="com.entity.PageBean">
    select
    <include refid="Base_Column_List" />
    from t_goods
    limit #{page},#{pageSize}
  </select>
           

因為傳入的參數類型是 PageBean 類型的 , 是以可以 直接通路到 其屬性 :page 和pageSize

2.用 Map 封裝傳遞

在 Mapper.java 中傳過來一個 map 類型的變量 ,其中設定有多對所要傳的 鍵值對 ,

在 Mapper.xml 中把參數類型寫為 map 類型的, 即: parameterType=“hashmap”,

在 放置變量的地方填寫 map 中的 鍵 就可以了

例如 : name = #{ name } and pwd = #{ pwd } name 和 pwd 都是 map中 的鍵 key

例子如下:

在 service 中 設定 map 的鍵值對:

Private User SelectUser(){  
   Map map=new hashMap();  
   map.put(“name”,”對應具體的參數值”);  
   map.put(“pwd”,”對應具體的參數值”);  
   User user=xxx. selectUser(map);}  
           

Mapper.java 中編寫方法,參數類型為 map

在 Mapper.xml 中編寫語句

<select id=" selectUser" resultMap="BaseResultMap">  
   select  *  from user_user_t   where user_name = #{name} and user_pwd=#{pwd }  
</select>
           

3.多個參數類型一樣的情況,可以直接傳入

當想要傳遞的多個參數,類型相同時, 可以在 Mapper.xml 傳參時 ,傳入那個相同的參數類型 . 例如 ,想要傳入兩個參數類型為 Long 的值 , 那麼就可以 進行如下操作:

在 Mapper.xml 中 編寫方法,傳入兩個 類型為 long 的參數

在 Mapper.xml 中編寫語句:

<select id="removeByPrimaryKey" parameterType="java.lang.Long">
    update
    t_goods
    set
    goodsStatus = 2
    where goodsId = #{goodsId} and  storeId= #{storeId}
  </select>
           

4.多個參數的類型不同時

所傳遞的多個值,采用 注解 的方式傳遞 , 文法格式為 :

在 Mapper.java 中

但是在 Mapper.xml 中接收的時候有兩種方式接收 ,

(1) 通過 索引 的方式接收,(不是很推薦)

<select id="findList" resultType="com.qcby.entity.User" >
   select
   <include refid="Base_Column_List" />
   from user
   where  user_name = #{ arg0 }   and  user_age=#{ arg1 }
   //或者寫為 where  user_name = #{ param1 }   and  user_age=#{ param2 } ...依次往下寫
 </select>
           

(2) 通過傳過來的名字擷取 , 即 @param()中的字元串 .

<select id="findList" resultType="com.qcby.entity.User" >
    select
    <include refid="Base_Column_List" />
    from user
    where  id = #{ name  } or 1=1 and account=#{ age  }
  </select>