11、mybatis学习——自定义结果映射resultMap以及关联查询

一、没有级联属性的情况时

  

   sqlmapper文件配置

    <!-- 自定义resultMap
            type:指定返回的类型;id:指定resultMap的唯一标识 -->
    <resultMap type="com.pxxy.bean.Employee" id="empMap">
        <id column="id" property="id"/>
        <!-- 列名和属性名一样的时候可以不写 -->
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
    </resultMap>
        
        <!-- 返回resultMap -->
    <select id="selectEmpById" resultMap="empMap">
        select * from employee where id = #{emp_id}
    </select>

  mapper接口定义方法

   测试方法:

二、有级联属性的情况时

    student关联college

 

    sqlmapper文件配置:

方式一:(以属性.属性进行传值)

 方式二:(以association的方式)

   mapper接口定义方法

   测试方法

三、有级联属性的情况时并使用分布查询

 student关联college

 

StudentMapper接口方法

 CollegeMapper接口方法

student的sqlmapper配置文件中配置分布查询

     <resultMap type="com.pxxy.bean.Student" id="stuStepMap">
         <id column="id" property="id"/>
         <!-- 列名和属性名一样的时候可以不写 -->
         <result column="name" property="name"/>
         <!-- association可以指定联合的javabean对象
             property="":指定哪个属性是联合的对象
             select:表明当前属性是调用select指定的方法查出的结果
             column:指定将哪一列的值传给这个方法作为参数
             流程:使用select指定的方法(传入column指定的值作为参数)查出对象,并封装给property指定的属性 -->
         <association property="college" 
             select="com.pxxy.bean.CollegeMapper.getColById"
             column="c_id">    <!-- 这里student表中的外键为c_id,查询时也没有取别名 -->
         </association>
     </resultMap>
     
     <select id="getStuByIdStep" resultMap="stuStepMap">
         select * from student where id=#{id}
     </select>

college的sqlmapper配置文件配置

<mapper namespace="com.pxxy.bean.CollegeMapper">
    <select id="getColById" resultType="college">
        select * from college where id = #{id}
    </select>
</mapper>

测试

    @Test
    public void testGetStuByIdStep() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        System.out.println(studentMapper.getStuByIdStep(1));
        sqlSession.close();
    }

原文地址:https://www.cnblogs.com/lyh233/p/12347818.html