老司机学习MyBatis之MyBatis如何使用Map处理参数

一、前言

如果多个参数不是业务模型中的数据,没有对应的POJO,为了方便,我们直接封装成Map传入。#{key}取出map中对应的值。

二、案例

在UserMapper.java增加查询方法findUserByMapParam,如下:

/**
 * 封装Map作为传递参数的载体
* @param user
* @return
 */
public User findUserByMapParam(Map map);

UserMapper.xml文件修改如下:

增加测试方法testMapParam如下:

@Test
public void testMapParam() throws IOException {
	SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
	SqlSession openSession = sqlSessionFactory.openSession();
	try {
		UserMapper mapper = openSession.getMapper(UserMapper.class);
		Map map =new HashMap();
		map.put("id", 1);
		User user = mapper.findUserByMapParam(map);
		System.out.println(user);
	} finally {
		openSession.close();
	}
}

测试查询功能,控制台打印如下:

2017-08-05 09:05:00,041 [main] [com.queen.mybatis.mapper.UserMapper.findUserByMapParam]-[DEBUG] ==>  Preparing: select id, loginId, userName, role, note from t_user where id = ? 
2017-08-05 09:05:00,108 [main] [com.queen.mybatis.mapper.UserMapper.findUserByMapParam]-[DEBUG] ==> Parameters: 1(Integer)
2017-08-05 09:05:00,158 [main] [com.queen.mybatis.mapper.UserMapper.findUserByMapParam]-[DEBUG] <==      Total: 1
User [id=1, loginId=queen, userName=奎恩, role=海贼王副把手, note=专门负责提鞋的。。。]


=======欢迎大家拍砖,小手一抖,多多点赞哟!=======

版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。


你可能感兴趣的:(MyBatis教程,老司机学习MyBatis)