mybatis参数传递(springboot)

本文详细介绍了MyBatis中各种参数的处理方式,包括单个参数、多个参数、带@Param注解的参数、对象参数、Map参数和注解对象参数的使用方法,以及参数在XML映射文件中的取值规则。重点讨论了参数在不同情况下的取值方式和解析机制,提供了具体的Mapper接口和XML配置示例。
摘要由CSDN通过智能技术生成

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

目录

单个参数

多个参数

带@Param注解的参数

对象参数

Map参数

注解对象参数


单个参数

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

Mapper接口中:

User selectById(int id);

Mapper.xml中:

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

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

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

多个参数

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

Mapper接口中:

User selectByMultiParam(int id,String name);

Mapper.xml中:

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

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

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

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

带@Param注解的参数

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

Mapper接口中:

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

Mapper.xml中:

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

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

对象参数

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

Mapper接口中:

User selectByBean(User user);

Mapper.xml中:

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

Map参数

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

测试类中:

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

Mapper接口中:

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

Mapper.xml中:

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

注解对象参数

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

Mapper接口中:

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

Mapper.xml中:

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值