您的位置:首页 > 其它

MyBatis输出映射为resultMap

2017-05-24 18:11 429 查看

MyBatis输出映射为resultMap

背景:使用resultType进行输出映射,必须保证查询结果的列名与pojo中国的属性名一致,该列才可以映射成功。

如果查询的列名与pojo中那属性名不一致就需要使用resultMap.

需求:从数据库查询出来的结果集有别名,需要映射到pojo类。

mapper.xml中定义resultMap

<!-- 自定义resultMap输出类型
type:查询结果最终映射的类型,可以是别名
id: resultMap的唯一标识
-->
<resultMap type="com.hl.myabtis.first.beas.User" id="userResultMap">
<!-- id:查询结果集中的唯一标识
column:对应列名
property:映射到pojo类中对应的属性名
-->
<id column="t_id" property="id"/>
<!--
result:除了唯一标识以外的字段
column:对应列名
property:映射到pojo类中对应的属性名
-->
<result column="t_username" property="username"/>
</resultMap>


使用resultMap

<!--
parameterType:输入参数类型
resultMap:输出参数类型
userResultMap:自定义resultMap
-->
<select id="findUserMapById" parameterType="int" resultMap="userResultMap">
select id t_id,username t_username from user where id=#{id}
</select>


定义mapper接口

//查询用户信心以map形式输出
public User findUserMapById(int id) throws Exception;


测试

@Test
public void findUserMapById() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
User user = usermapper.findUserMapById(3);
System.out.println(user);
sqlSession.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis