In the sample domain model, a tutor can teach one or more courses. This means that there is a one-to-many relationship between the tutor and course.

We can map one-to-many types of results to a collection of objects using the <collection> element.

The JavaBeans for Course and Tutor are as follows:

public class Course {
private Integer courseId;
private String name;
private String description;
private Date startDate;
private Date endDate;
private Integer tutorId; //setters & getters
} public class Tutor {
private Integer tutorId;
private String name;
private String email;
private Address address;
private List<Course> courses; //setters & getters
}

Now let us see how we can get the tutor's details along with the list of courses he/she teaches.
The <collection> element can be used to map multiple course rows to a list of course objects. Similar to one-to-one mapping, we can map one-to-many relationships using a nested ResultMap and nested Select approaches.

One-to-many mapping with nested ResultMap

We can get the tutor along with the courses' details using a nested ResultMap as follows:

<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<resultMap type="Tutor" id="TutorResult">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<collection property="courses" resultMap="CourseResult"/>
</resultMap> <select id="findTutorById" parameterType="int" resultMap="TutorResult">
SELECT T.TUTOR_ID, T.NAME AS TUTOR_NAME, EMAIL, C.COURSE_ID, C.NAME, DESCRIPTION, START_DATE, END_DATE
FROM TUTORS T LEFT OUTER JOIN ADDRESSES A ON T.ADDR_ID = A.ADDR_ID LEFT OUTER JOIN COURSES C ON T.TUTOR_ID = C.TUTOR_ID
WHERE T.TUTOR_ID = #{tutorId}
</select>

Here we are fetching the tutor along with the courses' details using a single Select query with JOINS. The <collection> element's resultMap is set to the resultMap ID CourseResult that contains the mapping for the Course object's properties.

One-to-many mapping with nested select

We can get the tutor along with the courses' details using a nested select query as follows:

<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<resultMap type="Tutor" id="TutorResult">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<association property="address" resultMap="AddressResult"/>
<collection property="courses" column="tutor_id" select="findCoursesByTutor"/>
</resultMap> <select id="findTutorById" parameterType="int" resultMap="TutorResult">
SELECT T.TUTOR_ID, T.NAME AS TUTOR_NAME, EMAIL FROM TUTORS T WHERE T.TUTOR_ID=#{tutorId}
</select>
<select id="findCoursesByTutor" parameterType="int" resultMap="CourseResult">
SELECT * FROM COURSES WHERE TUTOR_ID=#{tutorId}
</select>

In this approach, the <association> element's select attribute is set to the statement ID findCoursesByTutor that triggers a separate SQL query to load the courses' details. The tutor_id column value will be passed as input to the findCoursesByTutor statement.

public interface TutorMapper {
Tutor findTutorById(int tutorId);
} TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
Tutor tutor = mapper.findTutorById(tutorId);
System.out.println(tutor);
List<Course> courses = tutor.getCourses();
for (Course course : courses) {
System.out.println(course);
}

A nested select approach may result in N+1 select problems. First, the main query will be executed (1), and for every row returned by the first query, another select query will be executed (N queries for N rows). For large datasets, this could result in poor performance.

MyBatis(3.2.3) - One-to-many mapping的更多相关文章

  1. Mybatis 自动从数据库生成entity,mapping,dao接口

    1.下载需要的jar包 mybatis-generator-core-1.3.2.jar,mysql-connector-java-5.1.39.jar 2.把上面的jar包放到某个目录,并在该目录下 ...

  2. MyBatis---使用MyBatis Generator生成Dto、Dao、Mapping

    由于MyBatis属于一种半自动的ORM框架,所以主要的工作将是书写Mapping映射文件,但是由于手写映射文件很容易出错,所以查资料发现有现成的工具可以自动生成底层模型类.Dao接口类甚至Mappi ...

  3. mybatis-generator-gui--一个mybatis代码自动生成界面工具

    mybatis-generator-gui是什么 介绍mybatis-generator-gui之前,有必要介绍一下什么是mybatis generator(熟悉的同学可以跳过这一节).我们都知道,通 ...

  4. Mybatis映射文件

    Mapper XML 文件 MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行对比,你会 ...

  5. 整合spring,springmvc和mybatis

    我创建的是maven项目,使用到的依赖架包有下面这些: <dependencies> <dependency> <groupId>org.springframewo ...

  6. mybatis Mapper XML 文件

    MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% ...

  7. MyBatis《1》

     MyBatis入参考文档:http://mybatis.org/mybatis-3/zh/  1.使用MyBatis前的准备 1.增加Maven依赖 <dependency> <g ...

  8. Java数据持久层框架 MyBatis之API学习六(Mapper XML 文件详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  9. MyBatis学习总结(四)——MyBatis缓存与代码生成

    一.MyBatis缓存 缓存可以提高系统性能,可以加快访问速度,减轻服务器压力,带来更好的用户体验.缓存用空间换时间,好的缓存是缓存命中率高的且数据量小的.缓存是一种非常重要的技术. 1.0.再次封装 ...

  10. Spring Boot整合MyBatis(使用Spring Tool Suite工具)

    1. 创建Spring Boot项目 通过Spring Tool Suite的Spring Starter Project对话框,其实是把项目生成的工作委托http://start.spring.io ...

随机推荐

  1. Contest 7.23(不知道算什么)

    Problem A   URAL 1181 Cutting a Painted Polygon 题目大意就是说有一个N边形,让你做N-3条边,让他们的每个三角形的三个顶点颜色都不相同. 这里有一个引理 ...

  2. UVaLive 7359 Sum Kind Of Problem (数学,水题)

    题意:给定一个n,求前 n 个正整数,正奇数,正偶数之和. 析:没什么好说的,用前 n 项和公式即可. 代码如下: #pragma comment(linker, "/STACK:10240 ...

  3. 【JDBC】事务的使用

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5868750.html 关于事务的理论知识.ACID特性等等,网上太多了,在此不一一重复.本文主要着重  事务 ...

  4. poj1459

    初涉网络流.改日再写一些概念性的介绍. ek算法可作为模板使用. #include <iostream> #include <queue> using namespace st ...

  5. Http通讯协议在.net下的实现方法

    1.HttpwebRequest and  HttpWebResponse 2.客户端访问服务端的API:HttpClient 3. .net下的Remoting 4.Web Services 5.W ...

  6. getopt使用例子

    getopt是linux下获取程序启动参数的函数        #include <unistd.h> int getopt(int argc, char * const argv[], ...

  7. Date String转换

    这种转换要用到java.text.SimpleDateFormat类 字符串转换成日期类型: 方法1: 也是最简单的方法 Date date=new Date("2008-04-14&quo ...

  8. 单例模式总结(Java版)

    1:懒汉的设计模式,在第一次调用的时候才完成相关的初始化操作 懒汉式是典型的时间换空间,就是每次获取实例都会进行判断,看是否需要创建实例,浪费判断的时间.当然,如果一直没有人使用的话,那就不会创建实例 ...

  9. 关于.net中线程原子性的自我总结

    首先来张图,一张 cpu的简图,仅从个人理解角度理解画的 大体 解释下这张图 这是 一张 i5的简图i5 大家都知道 是双核四线程,(超线程技术)l1,l2,l3是 1,2,3级缓存. Cpu工作:每 ...

  10. JAVA反射机制学�

    JAVA反射机制:对于随意一个类,都可以知道这个类的全部属性和方法:对于随意一个对象,都可以调用它的随意一个方法和属性:这样的动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制. J ...