九、MyBatis参数处理

文章详细介绍了MyBatis框架中parameterType属性的用途,它是用来指定方法参数类型的,多数情况下可省略。当有多个参数时,MyBatis会创建一个Map,使用arg0/param1等作为key存储参数值。同时,使用@Param注解可以更明确地指定参数映射到SQL中的位置。
摘要由CSDN通过智能技术生成

1.单个参数

  • parameterType属性的作用:
    告诉mybatis框架,这个方法的参数类型是什么类型。
    mybatis框架自身带有类型自动推断机制,所以大部分情况下parameterType属性都是可以省略不写的。
    mybatis底层到底调用setXxx的哪个方法,取决于parameterType属性的值。
    java.lang.Long也可以写long,mybatis框架实际上内置了很多别名
<select id="selectById" resultType="Car" parameterType="java.lang.Long">
      select id,
              car_num as carNum,
              brand,
              guide_price as guidePrice,
              produce_time as produceTime,
              car_type as carType 
      from t_car where id = #{id}
</select>

2.多个参数

/**
* 多参数
* 根据carNum和guidePrice查询
*/
List<Car> selectByCarNumAndGuidePrice(String carNum, Double guidePrice);

mybatis底层会创建一个map集合,以arg0/param1为key,以方法上的参数为value

Map<String,Object> map = new HashMap<>();
map.put("arg0", carNum);
map.put("arg1", guidePrice);
map.put("param1", carNum);
map.put("param2", guidePrice);

所以可以这样取值:#{arg0} #{arg1} #{param1} #{param2}
其本质就是#{map集合的key}

<!--多参数-->
<select id="selectByCarNumAndGuidePrice" resultType="Car">
    select id,
           car_num as carNum,
           brand,
           guide_price as guidePrice,
           produce_time as produceTime,
           car_type as carType from t_car
     where car_num = #{arg0} and guide_price = #{arg1}
    <!--where car_num = #{param1} and guide_price = #{param2}-->
    <!--where car_num = #{arg0} and guide_price = #{param2}-->
</select>

使用Param注解

/**
* 多参数
* 根据carNum和guidePrice查询
*/
List<Car> selectByCarNumAndGuidePrice(@Param("carNum") String carNum, @Param("guidePrice") Double guidePrice);

select语句修改
使用了@Param注解之后,arg0和arg1失效了
param1和param2还可以用

<!--多参数-->
<select id="selectByCarNumAndGuidePrice" resultType="Car">
    select id,
           car_num as carNum,
           brand,
           guide_price as guidePrice,
           produce_time as produceTime,
           car_type as carType from t_car
    <!--where car_num = #{param1} and guide_price = #{param2}-->
	where car_num = #{carNum} and guide_price = #{guidePrice}
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值