MyBatis之@Param注解

编程入门 行业动态 更新时间:2024-10-23 05:44:10

MyBatis之@Param<a href=https://www.elefans.com/category/jswz/34/1768912.html style=注解"/>

MyBatis之@Param注解

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的属性

参考链接:

更多推荐

MyBatis之@Param注解

本文发布于:2024-02-05 09:12:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1674035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   MyBatis   Param

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!