MyBatis传递参数常用方式

一、匿名参数-顺序传递参数

必须按照顺序调用,且只能使用 [arg0、arg1]、[param0、param1]方式调用

String select(String a, String b);
<select id="select" resultTyp='string'>
	SELECT field FROM table where parma1 = #{param1} and parma2 = #{param2};
</select>

二、使用@Param注解

String select(@Param("username")String a, @Param("age")String b);
<select id="select" resultTyp='string'>
	SELECT field FROM table where parma1 = #{username} and parma2 = #{age};
</select>

三、使用Map传递参数

Map<String,String> params = new HashMap<>();
params.put("username","username");
params.put("age","age);
....
String select(Map<String,String> params);
<select id="select" resultTyp='string' parameterType="map">
	SELECT field FROM table where parma1 = #{username} and parma2 = #{age};
</select>

四、传递Java Bean

package com.Test.User

public class User {
	private String usernmae;
	private String age;
	....
}
....
String select(User params);
<select id="select" resultTyp='string' parameterType="com.Test.User">
	SELECT field FROM table where parma1 = #{username} and parma2 = #{age};
</select>

五、传递集合类型参数List、Set、Array

List<String> list = ...
...
String select(List<String> list);
<select id="select" resultTyp='string'>
	SELECT
		field
	FROM table where parmas in
	 <foreach collection="list" open="(" separator="," close=")" item="item">
      	#{item}
    </foreach>
</select>

foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名,
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
open表示该语句以什么开始,
separator表示在每次进行迭代之间以什么符号作为分隔符,
close表示以什么结束
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下几种情况:

  • 1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  • 2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  • 3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map或者Object
  • 4.使用@Param指定collection的属性值
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值