当前位置:   article > 正文

mybatis参数传递(springboot)_mybatis全局参数

mybatis全局参数

今天继续完善一下mybatis系列相关博客,以便查阅,同时也希望能帮助到有需要的小伙伴,各位看到此博客的小伙伴,如有不对的地方请及时通过私信我或者评论此博客的方式指出,以免误人子弟。多谢!

目录

单个参数

多个参数

带@Param注解的参数

对象参数

Map参数

注解对象参数


单个参数

接口传递单个参数时,在xml中接收参数的时候#{}中写什么都是可以的,不过通常为了方便理解,可以直接写与接口中传递的参数名一致即可,如:

Mapper接口中:

User selectById(int id);

Mapper.xml中:

  1. <select id="selectById" resultType="com.example.mybatis.domain.User">
  2. select * from t_user where id=#{id}
  3. </select>

上面说到,#{}中写什么都是可以的,比如随便写一个#{aaa} 也是可以的。

从源码参数解析类ParamNameResolver中来看,对于只有一个参数并且没有注解标记时,它总是返回参数的小标,通过下标取值。

多个参数

接口中传递多个参数时,可以通过#{arg0}...#{argn}或者下标#{param1}...#{paramn}取值。说到下标取值,其实严格来说springboot整合mybatis的start包来说,并不是真正的下标取值,因为前面加了一个param前缀,在mybatis中是可以通过真正的下标取值的,如:#{0},#{1}。

Mapper接口中:

User selectByMultiParam(int id,String name);

Mapper.xml中:

  1. <select id="selectByMultiParam" resultType="com.example.mybatis.domain.User">
  2. select *from t_user where id = #{param1} and name = #{param2}
  3. <!--where id = #{arg0} and name = #{arg1}-->
  4. </select>

多个参数的时候,mybatis最终会把参数封装到一个map中,"arg"+下标和"param"+下标会作为map的key,value就是我们最终想要获取的数据。

可能因为版本不同,之前参数解析完如下:

保险起见,取参数不要用arg使用param更稳妥。

带@Param注解的参数

接口参数中如果使用@Pram注解指定参数的名字可以使用指定名取值或下标取值。

Mapper接口中:

User selectByParamAnnotation(@Param("uid") int id,String name);

Mapper.xml中:

  1. <select id="selectByParamAnnotation" resultType="com.example.mybatis.domain.User">
  2. select * from t_user
  3. where id = #{uid} and name = #{param2}
  4. </select>

右上图可以看到,map中使用@param注解的别名uid作为了key,xml中就可以直接使用#{uid}取值。

对象参数

参数为对象可以使用#{对象的属性名}取值。

Mapper接口中:

User selectByBean(User user);

Mapper.xml中:

  1. <select id="selectByBean" resultType="com.example.mybatis.domain.User">
  2. select * from t_user where id = #{id} and name = #{name}
  3. </select>

Map参数

map类型的参数可以直接通过map的key取值#{key}

测试类中:

  1. Map<String, Object> map = new HashMap<>();
  2. map.put("id",1);
  3. map.put("name","zhangsan");

Mapper接口中:

User selectByMap(Map<String,Object> map);

Mapper.xml中:

  1. <select id="selectByMap" resultType="com.example.mybatis.domain.User">
  2. select * from t_user where id = #{id} and name = #{name}
  3. </select>

注解对象参数

注解的对象作为参数,可以通过 #{注解的别名.属性} 的方式取值,当然你也可以通过#{param1.属性名}的方式取值。。

Mapper接口中:

User selectByBeanParam(@Param("u") User user);

Mapper.xml中:

  1. <select id="selectByBeanParam" resultType="com.example.mybatis.domain.User">
  2. select * from t_user where name = #{u.name}
  3. </select>

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号