MyBatis输出映射为resultMap

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值