Copyright: https://blog.csdn.net/Dongguabai/article/details/90246717
Wrote a blog before, MyBatis return a result of type Map ( https://blog.csdn.net/Dongguabai/article/details/79580200 ), this direct return results Map, the result returned is this:
The result is a return Map, Map of Entry for the "field name - field value, the field name - field value."
But sometimes we need is the return of key-value, key and value are two mapping relational data returned. This time you can do:
Custom Handler achieve ResultHandler:
/**
* @author dongguabai
* @Description
* @Date 创建于 2019-05-15 22:14
*/
public class MapResultHandler implements ResultHandler {
private final Map mappedResults = new HashMap();
@Override
public void handleResult(ResultContext context) {
@SuppressWarnings("rawtypes")
Map map = (Map)context.getResultObject();
mappedResults.put(map.get("key"), map.get("value"));
}
public Map getMappedResults() {
return mappedResults;
}
}
Mapper (time to address the situation when a method with parameters, where a query Query added):
public interface UserAccountMapper extends BaseMapper<UserAccount> {
Map<String,String> testType(UserQuery query);
}
xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zj.bda.persistence.mapper.UserAccountMapper">
<resultMap id="mapResult" type="java.util.HashMap">
<result property="key" column="username"/>
<result property="value" column="balance" />
</resultMap>
<select id="testType" parameterType="com.zj.bda.persistence.query.UserQuery" resultMap="mapResult">
select username,balance from user_account where username = #{username} and balance = #{balance}
</select>
</mapper>
database:
test:
/**
* @author Dongguabai
* @date 2018/10/8 10:25
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootSpringTest {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Test
public void test2(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
MapResultHandler handler = new MapResultHandler();
UserQuery userQuery = new UserQuery("zhangsan",2000);
sqlSession.select("com.zj.bda.persistence.mapper.UserAccountMapper.testType",userQuery,handler);
//获取结果
handler.getMappedResults().forEach((k,v)-> System.out.println("k:"+k+",v:"+v));
}}