【详解】@Param注解的用法

114 篇文章 0 订阅
113 篇文章 1 订阅

1、概述

首先明确这个注解是为SQL语句中参数赋值而服务的。

@Param的作用就是给参数命名,比如在mapper里面某方法A(int id),当添加注解后A(@Param(“userId”) int id),也就是说外部想要取出传入的id值,只需要取它的参数名userId就可以了。将参数值传如SQL语句中,通过#{userId}进行取值给SQL的参数赋值。

2、实例:

实例一:@Param注解基本类型的参数

mapper中的方法:

public User selectUser(@Param("userName") String name,@Param("password") String pwd);

映射到xml中的标签

<select id="selectUser" resultMap="User">  
   select * from user  where user_name = #{userName} and user_password=#{password}  
</select>

其中where user_name = #{userName} and user_password = #{password}中的userName和password都是从注解@Param()里面取出来的,取出来的值就是方法中形式参数 String name 和 String pwd的值。

实例二:@Param注解JavaBean对象

SQL语句通过@Param注解中的别名把对象中的属性取出来然后复制

mapper中的方法:

public List<User> getAllUser(@Param("user") User u);

映射到xml中的标签

<select id="getAllUser" parameterType="com.vo.User" resultMap="userMapper">  
        select   
        from user t where 1=1  
             and   t.user_name = #{user.userName}  
              and   t.user_age = #{user.userAge}  
    </select>  

3、注意点

当使用了@Param注解来声明参数的时候,SQL语句取值使用#{},${}取值都可以。

当不使用@Param注解声明参数的时候,必须使用的是#{}来取参数。使用${}方式取值会报错。

不使用@Param注解时,参数只能有一个,并且是Javabean。在SQL语句里可以引用JavaBean的属性,而且只能引用JavaBean的属性。

??? @Select("SELECT * from Table where id = #{id}")
?? ?Enchashment selectUserById(User user);
  • 22
    点赞
  • 143
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值