Mybatis中@Param的用法和作用详解

xiaoxiao2021-02-28  26

用注解来简化xml配置的时候,@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中

我们先来看Mapper接口中的@Select方法

? 1 2 3 4 5 6 7 package Mapper; public interface Mapper { @Select ( "select s_id id,s_name name,class_id classid from student where s_name= #{aaaa} and class_id = #{bbbb}" )    public Student select( @Param ( "aaaa" ) String name, @Param ( "bbbb" ) int class_id); @Delete ...... @Insert ...... }   

这里解释一下

1.@Select(....)注解的作用就是告诉mybatis框架,执行括号内的sql语句

2.s_id id,s_name name,class_id classid  格式是 字段名+属性名,例如s_id是数据库中的字段名,id是类中的属性名

    这段代码的作用就是实现数据库字段名和实体类属性的一一映射,不然数据库不知道如何匹配

3.where  s_name= #{aaaa} and class_id = #{bbbb} 表示sql语句要接受2个参数,一个参数名是aaaa,一个参数名是bbbb,如果要正确的传入参数,那么就要给参数命名,因为不用xml配置文件,那么我们就要用别的方式来给参数命名,这个方式就是@Param注解

4.在方法参数的前面写上@Param("参数名"),表示给参数命名,名称就是括号中的内容

? 1 public Student select( @Param ( "aaaa" ) String name, @Param ( "bbbb" ) int class_id);

给入参 String name 命名为aaaa,然后sql语句....where  s_name= #{aaaa} 中就可以根据aaaa得到参数值了

PS:下面看下spring中@param和mybatis中@param使用区别

1.spring中@param

? 1 2 3 4 5 6 /**    * 查询指定用户和企业关联有没有配置角色    * @param businessId memberId    * @return    */    int selectRoleCount( @Param ( "businessId" ) Integer businessId, @Param ( "memberId" ) Long memberId);

2.mybatis中的param

? 1 2 3 4 5 6 /**   * 查询指定用户和企业关联有没有配置角色   * @param businessId memberId   * @return   */   int selectRoleCount( @Param ( "businessId" ) Integer businessId, @Param ( "memberId" ) Long memberId);

从表面上看,两种并没有区别,但是在xml文件中使用的时候是有区别的,Spring中的@param在xml需要如下这样引用变量

? 1 2 3 4 5 6 7 8 <select id= "selectRoleCount" resultType= "java.lang.Integer" > select    count(tbm.id)    from t_business_member_relation tbm    where tbm.business_id = #{ 0 ,jdbcType=INTEGER}    and tbm.member_id = #{ 1 ,jdbcType=INTEGER}    and tbm.role_business_id is not null </select>

是根据参数的顺序来取值的,并且从0开始。而在mybatis @param在xml中则是如下这样引用变量的

? 1 2 3 4 5 6 7 8 <select id= "selectRoleCount" resultType= "java.lang.Integer" >    select    count(tbm.id)    from t_business_member_relation tbm    where tbm.business_id = #{businessId,jdbcType=INTEGER}    and tbm.member_id = #{memberId,jdbcType=INTEGER}    and tbm.role_business_id is not null   </select>

是通过参数名来引用的

注:如果Mapper.java文件中引用的是Spring的

? 1 org.springframework.data.repository.query.Param;

但是Mapper.xml中使用的是mybatis 的用法,那么就会如下的错误

? 1 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'businessId' not found. Available parameters are [ 1 , 0 , param1, param2]

截图如下

 

所以在使用的时候一定要注意@param引用和使用的一致性

转载请注明原文地址: https://www.6miu.com/read-2595511.html

最新回复(0)