-
<李>前几天恰好面试一个应届生,问了一个很简单的问题:你了解过Mybatis中有几种传参方式吗?李>
<李>没想到其他问题回答的很好,唯独这个问题一知半解,勉强回答了其中两种方式。李>
<李>于是这篇文章就来说一说Mybatis传参的几种常见方式,给正在面试或者准备面试的朋友巩固一下。李>
单个参数的传参比较简单,可以是任意形式的,比如<代码> #{一}代码>,<代码> # {b}> 代码或者<代码> # {param1}, 代码>但是为了开发规范,尽量使用和入参时一样。
映射器如下:
用户信息selectByUserId (String userId);
XML如下:
& lt;选择id=" selectByUserId " resultType=癱n.cb.demo.domain.UserInfo”比; select * from user_info user_id==1 # {userId}和状态 & lt;/select>
多个参数的情况下有很多种传参的方式,下面一一介绍。
-
<李>多个参数可以使用类似于索引的方式传值,比如<代码> # {param1} 代码>对应第一个参数,# {param2}对应第二个参数.......李>
<李>映射器方法如下:李>
用户信息selectByUserIdAndStatus (String userId,整数地位);
XML如下:
& lt;选择id=" selectByUserIdAndStatus " resultType=癱n.cb.demo.domain.UserInfo”比; select * from user_info user_id=# {param1}和状态=# {param2} & lt;/select>
注意:由于开发规范,此种方式不推荐开发中使用。
@Param这个注解用于指定键,一旦指定了钥匙,在SQL中即可对应的关键入参。
映射器方法如下:
用户信息selectByUserIdAndStatus (@Param (userId)字符串userId, @Param(“状态”)整数状态),
XML如下:
& lt;选择id=" selectByUserIdAndStatus " resultType=癱n.cb.demo.domain.UserInfo”比; select * from user_info user_id=# {userId}和状态=#{地位} & lt;/select>
Mybatis底层就是将入参转换成地图,入参传地图当然也行,此时<代码> #{关键}代码>中的关键就对应的地图中的关键。
映射器中的方法如下:
用户信息selectByUserIdAndStatusMap (Map<字符串,Object>地图);
XML如下:
& lt;选择id=" selectByUserIdAndStatusMap " resultType=癱n.cb.demo.domain.UserInfo”比; select * from user_info user_id=# {userId}和状态=#{地位} & lt;/select>
测试如下:
@Test 空白contextLoads () { Object> Map<字符串;地图=new HashMap<在(); map.put(“标识”,“1222”); map.put(“地位”,1); 用户信息用户信息=userMapper.selectByUserIdAndStatusMap(地图); System.out.println(用户信息); }
多个参数可以使用实体类封装,此时对应的关键就是属性名称,注意一定要有得到方法。
映射器方法如下:
用户信息selectByEntity (UserInfoReq UserInfoReq);
XML如下:
& lt;选择id=" selectByEntity " resultType=癱n.cb.demo.domain.UserInfo”比; select * from user_info user_id=# {userId}和状态=#{地位} & lt;/select>
实体类如下:
@ data 公开课UserInfoReq { 私人字符串标识; 私人整数状态; }
名单传参也是比较常见的,通常是SQL中的。
映射器方法如下:
ListselectList (List 用户id);
XML如下:
& lt;选择id=" selectList " resultMap=皍serResultMap”比; select *从user_info状态=1 和user_id & lt; foreach收集=傲斜怼毕?毕钅俊翱??“分隔符=薄ⅰ??”比; #{项} & lt;/foreach> & lt;/select>
这种方式类似名单传参,依旧使用foreach <代码> 代码>语法。
映射器方法如下: