我如何传递参数并在mybatis动态查询创建中检查它

时间:2012-09-28 15:46:06

标签: ibatis mybatis

我在mapper.xml

中写了一个选择查询
<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类的整个对象?

1 个答案:

答案 0 :(得分: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 mapper将是我所说的,但使用cat_type_id代替param1

相关问题