[mybatis]ResultMap输出结果映射

为什么会有ResultMap?

    

使用ResultMap,在mapper.xml中配置 :




<mapper namespace="mapper.UserMapper" >
    
    <resultMap type="user" id="userResultMap">
        
        <id column="id_" property="id" />
        
        <result column="username_" property="username" />
    resultMap>
    
    <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
        SELECT id id_ , username username_ FROM USER WHERE ID=#{id}
    select>
mapper>

Mapper接口中的方法定义:

    //根据id查找用户,返回resultMap
    public User findUserByIdResultMap (int id) ;

方法测试 :

    //根据id查找用户,返回resultMap
    @Test
    public void testFindUserByIdResultMap (){
        //创建session
        SqlSession session = sessionFactory.openSession();
        //通过session获取mapper代理
        UserMapper mapper = session.getMapper(UserMapper.class);
        //调用代理接口中的方法
        User user = mapper.findUserByIdResultMap(3);
        //输出user
        System.out.println(user);
    }   

你可能感兴趣的:(MyBatis)