MyBatis输出映射为resultMap

来源:互联网 发布:055大驱数据 编辑:程序博客网 时间:2024/05/22 23:59

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();    }
原创粉丝点击