温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Mybatis在什么情况下需要使用@param注解

发布时间:2020-11-05 18:50:33 来源:亿速云 阅读:1763 作者:Leah 栏目:开发技术

这篇文章运用简单易懂的例子给大家介绍Mybatis在什么情况下需要使用@param注解,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

一、方法有多个参数

例如:

接口方法:

@Mapper
public interface UserMapper {
  Integer insert(@Param("username") String username, @Param("address") String address);
}

对应的xml:

<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
  insert into user (username,address) values (#{username},#{address});
</insert>

原因:当不使用 @Param 注解时,mybatis 是不认识哪个参数叫什么名字的,尽管在接口中定义了参数的名称,mybatis仍然不认识。这时mybatis将会以接口中参数定义的顺序和SQL语句中的表达式进行映射,这是默认的。

二、方法参数要取别名

例如

@Mapper
public interface UserMapper {
  Integer insert(@Param("username") String username, @Param("address") String address);
}

对应的xml:

<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
  insert into user (username,address) values (#{username},#{address});
</insert>

三、XML 中的 SQL 使用了 $ 拼接sql

$ 会有注入的问题,但是有的时候不得不使用 $ 符号,例如要传入列名或者表名的时候,这个时候必须要添加 @Param 注解

例如:

@Mapper
public interface UserMapper {
  List<User> getAllUsers(@Param("order_by")String order_by);
}

对应xml:

<select id="getAllUsers" resultType="org.javaboy.helloboot.bean.User">
  select * from user
  <if test="order_by!=null and order_by!=''">
    order by ${order_by} desc
  </if>
</select>

四、动态 SQL 中使用了参数作为变量

如果在动态 SQL 中使用参数作为变量,那么也需要 @Param 注解,即使你只有一个参数。例如如下方法:

@Mapper
public interface UserMapper {
  List<User> getUserById(@Param("id")Integer id);
}

对应xml:

<select id="getUserById" resultType="org.javaboy.helloboot.bean.User">
  select * from user
  <if test="id!=null">
    where id=#{id}
  </if>
</select>

关于Mybatis在什么情况下需要使用@param注解就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI