parameterType指定HashMap传递输入参数,“#{}”和“${}”中自动识别Map的key,并替换参数
SQL映射文件定义如下:传入的参数类型是HashMap
<!--传递HashMap综合查询用户信息 -->
<select id="selectUserByHashmap"
parameterType="hashmap" resultType="user">
select * from user where id=#{id} and username like '%${username}%'
</select>
1、在UserMapper.xml中添加如下SQL
<!-- 使用的是HashMap作为参数查询
sex和username表示的是HashMap的key,参数使用的是别名
-->
<select id="findUserListByMap" parameterType="hashmap"
resultType="UserCustom">
select * from user where user.sex = #{sex}
and user.username like '%${username}%'
</select>
2、在UserMapper.java中定义如下方法
/**
* 使用HashMap作为参数查询结果集
* @param param
* @return
* @throws Exception
*/
List<UserCustom> findUserListByMap(Map<String, String> param) throws Exception;
3、编写测试方法进行测试
/**
* 使用HashMap作为参数查询结果集
* @throws Exception
*/
@Test
public void testFindUserListByMap() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建UserMapper对象,mybatis自动生成mapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//组装查询条件
Map<String, String> param = new HashMap<String, String>();
param.put("sex", "1");
param.put("username", "张");
List<UserCustom> users = userMapper.findUserListByMap(param);
System.out.println(users);
}