一文学会Mybatis Mybatis传入参数及返回类型

一、Mybatis的三种传入参数的方式

1. 根据下标索引传值

通过传递参数的顺序进行索引,获得参数的值

Public User selectUser(String name,String area);


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

其中#{0} 代表传入的第一个参数,之后依次进行索引。

2. 使用@param注解进行参数传递

先看例子:

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


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

这种方法通过定义注解,设定参数的key值,在mapper.xml中通过key值进行获取,这种方法较为直观,但是参数数量较为固定。

3、通过map传递参数

Public User selectUser(Map paramMap);


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

通过map的方式进行参数传递不需要固定参数的数量,在mapper中直接通过key值获得参数的值。

小结

这几种参数传递的方式每个人有每个人的习惯,可以在具体的项目中根据自己的使用习惯进行选择。

二、Mybatis的返回类型

1、返回参数类型

MyBatis的返回参数类型分两种

参数类型对应的返回值类型
resultMap可以返回一个list,也可以返回一个实体
resultTypeint、string、long、class(实体)

2、 指定返回resultType


<select id="queryCategoryBrandCount" resultType="java.lang.Integer" parameterType="java.util.HashMap" >  
        select count(1)  
        from common_category_brand  
        where 1=1  
        <if test="categoryId != null" >  
            and category_id = #{categoryId,jdbcType=BIGINT}  
        </if>  
        <if test="brandId != null" >  
            and brand_id = #{brandId,jdbcType=BIGINT}  
        </if>  
    </select>  

3、 指定返回resultMap

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >  
    select   
    <include refid="Base_Column_List" />  
    from common_car_make  
    where id = #{id,jdbcType=BIGINT}  
  </select>  

在返回ResultMap时,需要对之前对BaseResultMap中返回的值的类型进行指定,在执行select语句时返回相应的resultMap

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值