Mybatis之resultMap的使用(19)

博客介绍了Mybatis中使用resultMap完成高级输出结果映射的方法。当查询列名和pojo属性名不一致时,可定义resultMap建立映射关系。还给出了将SQL使用User进行映射的具体步骤,最后总结了resultMap的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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属性名之间作一个映射关系。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值