MyBatis传递多个参数的4种方式

本文介绍了MyBatis中四种传递多个参数的方法:通过Map、使用注解、通过JavaBean及混合使用。并针对每种方式的特点进行了总结,旨在帮助开发者选择最适合场景的参数传递方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.map接口传递参数

接口参数为Map,通过key值映射

public List<Role> findRolesByMap(Map<String,Object> parameterMap);
<select id="findRolesByMap" parameterType="map" resultType="role">
	select name,email,phone from t_role where username=#{username} and password=#{password}
</select>

通过map的键名去匹配值

2.使用注解传递多个参数

public List<Role> findRolesByAnno(@Param("username")String username,@Param("password")String password);
<select id="findRolesByAnno" resultType="role">
	select name,email,phone from t_role where username=#{username} and password=#{password}
</select>

使用注解方式无需写parameterType属性,MyBatis会自动匹配

3.通过JavaBean传递

class Bean {
	String password;
	String username;
	//getter setter 方法
}
public List<Role> findRolesByBean(Bean bean);
<select id="findRolesByBean" parameterType="Bean全类名" resultType="role">
	select name,email,phone from t_role where username=#{username} and password=#{password}
</select>

bean类需要写get和set方法,parameterType需要写全类名

4.混合使用

class Bean {
	String password;
	String username;
	//getter setter 方法
}
class Bean2 {
	String sex;
	String phone;
	//getter setter 方法
}
public List<Role> findRolesByMix(@Params("bean1")Bean1 bean1,@Params("bean2")Bean2 bean2);
<select id="findRolesByMix"  resultType="role">
	select name,email,phone from t_role where username=#{bean1.usernmae} and password=#{bean1.password} and sex=#{bean2.sex}
</select>

这是混合了注解与bean传参的方式,用到了注解传参,也无需写parametersType属性

总结

总结:
1.使用map传参导致了业务可读性的丧失,因为必须要阅读其键值才知道其作用,扩展可维护性差,最好不要使用该方式。
2.使用@Param参数,在参数<=5个的时候推荐使用,参数较多时建议使用JavaBean的方式,因为更加直观
3.对于使用混合参数的,要明确参数的合理性
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值