前言
这里为了简单的说明问题,抽取接口、mapper.xml映射文件和测试类调用方法的部分代码作为说明。
一、问题
接口
List<User> selectUserByCondition(String username, String sex);
映射文件
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{username} and sex = #{sex};
</select>
测试类
List<User> users = userMapper.selectUserByCondition("%天%", "男");
在使用mybatis框架的时候,如果接口方法需要传入的参数是多个,这个是很好就会报错。
Cause: org.apache.ibatis.binding.BindingException: Parameter ‘username’ not found. Available parameters are [arg1, arg0, param1, param2]
因为mybatis不能识别多个参数。
但是有默认的解决的方案:
接口
List<User> selectUserByCondition(String username, String sex);
映射文件
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{arg0} and sex = #{arg1};
</select>
或者
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{param1} and sex = #{param2};
</select>
测试类
List<User> users = userMapper.selectUserByCondition("%天%", "男");
这样可以解决传入多个参数的区别,但是缺点就是如果参数过于多,映射文件可读性差,所以一般不采用默认参数,一般采用以下三种方法处理。
二、解决方案
2.1 1 散装参数
如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
接口:
//相当于给默认参数起别名
List<User> selectUserByCondition(@Param("username") String username, @Param("sex") String sex);
映射文件
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{username} and sex = #{sex};
</select>
测试类
List<User> users = userMapper.selectUserByCondition("%天%", "男");
2.1.2 对象参数
对象的属性名称要和参数占位符名称一致
接口
List<User> selectUserByCondition(User user);
映射文件
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{username} and sex = #{sex};
</select>
测试类
User user = new User();
user.setUsername("%天%");
user.setSex("男");
List<User> users = userMapper.selectUserByCondition(user);
for (User rs : users) {
System.out.println(rs);
}
对象的属性值需要和参数占位符名称一致,mybatis会自动解析取出对应值匹配。
2.2.3 Map参数集合
Map的键要和占位符名称一致
接口
List<User> selectUserByCondition(Map<String,String> map);
映射文件
<select id="selectUserByCondition" resultType="User">
select * from user where username like #{username} and sex = #{sex};
</select>
测试类
Map<String, String> map = new HashMap<>();
map.put("username", "%天%");
map.put("sex", "男");
List<User> users = userMapper.selectUserByCondition(map);
键值需要和占位符参数名一致,mybatis会自动解析map集合取键对应值进行匹配。
总结
解决mybatis方法传入多个参数,主要有三个方法。
①散装参数: 如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
②对象参数: 对象的属性名称要和参数占位符名称一致。
③Map集合参数: Map的键要和占位符名称一致。