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();
    }
复制代码

 

posted @   Arbitrary233  阅读(459)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示