2012-09-28 18 views
2

我已經寫在我的mapper.xml我將如何傳遞參數,並檢查它在MyBatis的動態查詢創建

<select id="getCatCount" parameterType="String" resultType="int"> 
    select count(*) from Categories where status is not null 
    <if test="catTypeId != 0"> 
    AND cat_type_id = #{catTypeId,jdbcType=INTEGER} 
    </if> 
</select> 

和mapper.java方法的選擇查詢

int getCatCount(int catTypeId); 

我如何檢查在if條件中爲catTypeId。我知道上面的語句是不正確的,但我想把這樣的條件,所以我檢查catTypeId是否不爲零,然後只添加AND條件。或者我需要傳遞Category類的整個對象嗎?

回答

5

您不需要傳遞整個Category類。只要做到這一點,你所描述:

int getCatCount(int catTypeId); 

你mapper.xml應該是這樣的:

<select id="getCatCount" parameterClass="map" resultType="int"> 
    select count(*) from Categories where status is not null 
    <if test="param1 != 0"> 
    AND cat_type_id = #{param1,jdbcType=INTEGER} 
    </if> 
</select> 

注意,作爲parameterClass你需要指定一個地圖。

比方說,現在,你想傳遞兩個參數:

int getCatCount(int catTypeId, int mySecondParam); 

在映射器,您應該param1param2

看,你如何需要使用「paramX」的命名工作。但是,讓我們說,相反使用該命名法,您希望將自定義參數名稱用作「catTypeId」。對於這一點,在你的Java代碼,你需要做的:

int getCatCount(@Param("cat_type_id ") String cat_type_id); 

的XML映射器將是一個,我把它有關,但使用cat_type_id代替param1

+0

非常感謝Jddsantaella多一次和非常好的解釋。 – user965884

+0

不客氣。 – jddsantaella

+0

這真的幫助我理解一個新的api怪癖 – Stevko