目录
1.概述
首先明确这个注解是为SQL语句中参数赋值而服务的。
@Param的作用就是给参数起别名,比如在mapper里面某方法A(int id),当添加注解后A(@Param("userId") int id),sql中要想使用id的值,只需要取它的参数名userId就可以了。将参数值传如SQL语句中,通过#{userId}进行取值给SQL的参数赋值。
2.示例
(1)@Param注解基本类型的参数
mapper的方法
public User selectUser(@Param("userName") String name,@Param("password") String pwd);
映射文件中的方法
<select id="selectUser" resultMap="User">
select * from user where user_name = #{userName} and user_password=#{password}
</select>
(2)@Param注解JavaBean对象
SQL语句通过@Param注解中的别名把对象中的属性取出来
mapper中的方法
public List<User> getAllUser(@Param("user") User u);
映射文件中的方法
<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注解也可以