1. 程式人生 > >Mybatis傳遞多個引數的解決辦法(三種)

Mybatis傳遞多個引數的解決辦法(三種)

第一種方案

DAO層的函式方法

Public User selectUser(String name,String area);

對應的Mapper.xml

<select id="selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{0} and user_area=#{1}
</select>

其中,#{0}代表接收的是dao層中的第一個引數,#{1}代表dao層中第二引數,更多引數一致往後加即可。

第二種方案

此方法採用Map傳多引數.

Dao層的函式方法

Public User selectUser(Map paramMap);

對應的Mapper.xml

<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select>

Service層呼叫

Private User xxxSelectUser(){
Map paramMap=new hashMap();
paramMap.put(“userName”,”對應具體的引數值”);
paramMap.put(“userArea”,”對應具體的引數值”);
User user=xxx. selectUser(paramMap);}

個人認為此方法不夠直觀,見到介面方法不能直接的知道要傳的引數是什麼。

第三種方案

Dao層的函式方法

Public User selectUser(@param(“userName”)Stringname,@param(“userArea”)String area);

對應的Mapper.xml

<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select> 

個人覺得這種方法比較好,能讓開發者看到dao層方法就知道該傳什麼樣的引數,比較直觀,個人推薦用此種方案。