myBatis的@Param注解和参数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22078107/article/details/85761553

关于Mybatis @Param 注解,官方文档: http://www.mybatis.org/mybatis-3/zh/java-api.html
其中关于 @param部分的说明是:

    @Param Parameter N/A 如果你的映射器的方法需要多个参数, 这个注解可以被应用于映射器的方法 参数来给每个参数一个名字。否则,多 参数将会以它们的顺序位置来被命名 (不包括任何 RowBounds 参数) 比如。 #{param1} , #{param2} 等 , 这 是 默 认 的 。 使 用 @Param(“person”),参数应该被命名为 #{person}。

也就是说如果有多个参数的时候,可以使用@Param 这个注解

 

  • 使用@Param注解

当以下面的方式进行写SQL语句时:

    @Select("select column from table where userid = #{userid} ")
    public int selectColumn(int userid);

当你使用了使用@Param注解来声明参数时,如果使用 #{} 或 ${} 的方式都可以。

    @Select("select column from table where userid = ${userid} ")
    public int selectColumn(@Param("userid") int userid);

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

    @Select("select column from table where userid = ${userid} ")
    public int selectColumn(@Param("userid") int userid);

  • 不使用@Param注解

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

    // 这里id是user的属性

    @Select("SELECT * from Table where id = ${id}")
    Enchashment selectUserById(User user);

另外推荐下比较好的关于@Param注解的解释

 

猜你喜欢

转载自blog.csdn.net/qq_22078107/article/details/85761553