Mybatis中使用resultMap完成高级输出结果映射。
一、resultMap使用方法
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射。
1、定义resultMap
2、使用resultMap作为statement的输出映射类型
二、将下边的SQL使用User进行映射
select id id_, username username_ from user where id=#{value}
userCUstom类中属性名和上边查询列名不一致。1、定义ResultMap
在UserMapper.xml中定义如下resultMap:
<!-- 定义resultMap
将select id id_, username username_ from user和User类中的属性作一个映射
type:resultMap最终映射的java对象类型,可以使用别名
id:对resultMap的唯一标识
-->
<resultMap type="User" id="userResultMap">
<!-- id表示查询结果集唯一标识
column:查询出来的列名
property:type指定的pojo类型中的属性名
最终resultMap对column和property作为一个映射关系(对应关系)
-->
<id column="id_" property="id" />
<!--
result:对普通的列映射定义
column:查询出来的列名
property:type指定的pojo类型中的属性名
最终resultMap对column和property作为一个映射关系(对应关系)
-->
<result column="username_" property="username" />
</resultMap>
2、使用resultMap作为statement的输出映射类型在UserMapper.xml中使用上面定义的resultMap:
<!-- 使用resultMap进行输出映射
resultMap:指定定义的resultMap的id,如果这个resultMap在其它的mapper文件,
前边需要加namespce
-->
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
select id id_, username username_ from user where id=#{value}
</select>
3、在UserMapper.java中声明如下方法
/**
* 根据id查询用户,通过resultMap进行映射
* @param id
* @return
* @throws Exception
*/
public User findUserByIdResultMap(int id) throws Exception;
4、编写测试方法进行测试
@Test
public void testFindUserByIdResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建UserMapper对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用userMapper的方法
User user = userMapper.findUserByIdResultMap(1);
sqlSession.close();
System.out.println(user);
}
三、小结
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。