Mybatis各种传参方式

1.传入单个参数

传入单个参数有两种写法,其一就是我们常用的使用实体类属性名传入,如下:

UserManage selectByPrimaryKey(String userId);

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select  *
    from USER_MANAGE
    where USER_ID = #{userId,jdbcType=VARCHAR}
</select>
其二就是使用占位符传入,如下:

UserManage selectByPrimaryKey(String userId);

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select  *
    from USER_MANAGE
    where USER_ID = #{0}
</select>

2.传入多个参数

传入多个参数同样有两种写法,其一也是使用实体类属性名传入,如下:

UserManage selectByUserIdAndUserName(String userId,String userName);

<select id="selectByUserIdAndUserName" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select  *
    from USER_MANAGE
    where USER_ID = #{userId,jdbcType=VARCHAR} and USER_NAME = #{userName,jdbcType=VARCHAR}
</select>
其二就是使用占位符传入,如下:

UserManage selectByUserIdAndUserName(String userId,String userName);

<select id="selectByUserIdAndUserName" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select  *
    from USER_MANAGE
    where USER_ID = #{0} and USER_NAME = #{1}
</select>

3.传入Map参数

map参数传入是我经常使用的,这个比较简单,使用起来我认为比较方便的,举个例子吧:

参数map:
Map<String,Object> map = new Map<String,Object>();
map.put("userId",userId);
map.put("userName",userName);

dao:
UserManage selectByUserIdAndUserName(Map<String,Object> map);

xml:
<select id="selectByUserIdAndUserName" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select  *
    from USER_MANAGE
    where USER_ID = ${userId} and USER_NAME = ${userName}
</select>
这里注意一点,xml中不在使用#,而是使用$,切记。

4.传入list参数

传入list参数这个我们一把用于批量插入,也是比较简单,我这里list中存的实体对象,举个例子:

参数map:
List<UserManage> list = new ArrayList<UserManage>();

dao:
int insertBatch(List<UserManage> list);

xml:
<insert id="insertBatch" parameterType="ArrayList">
	 insert into USER_MANAGE(USER_ID,USER_NAME)
		<foreach collection="list" item="item" index="index" separator="union all">
		   select #{item.userId,jdbcType=VARCHAR}, #{item.userName,jdbcType=VARCHAR} from dual
		</foreach>
</insert>
当然还有一种是list中存的是map对象,这种存入方式请看另外一篇博文:


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值