MyBatis(3.2.3) - One-to-many mapping

时间:2021-11-29 21:58:02

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&comma;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. 如何在MATLAB R2010a 中使用Visual C&plus;&plus; 2010编译器

    安装补丁VS2012MEXSupport.zip http://www.mathworks.com/matlabcentral/answers/93013-how-can-i-use-microsof ...

  2. sqlserver表分区

    参考:http://www.cnblogs.com/knowledgesea/p/3696912.html 及百度搜索sqlserver表分区 create partition function sg ...

  3. &lbrack;开发环境&rsqb; Ubuntu12&period;04 Telnet服务设置

    Ubuntu12.04默认未启用Telnet服务,配置Telnet服务步骤如下: 1. 安装和配置 安装openbsd-inetd: #sudo apt-get install openbsd-ine ...

  4. 通过Jetty搭建一个简单的Servlet运行环境

    最近在做一些简单的Servlet开发的时候,感觉每次调试的时候都要发布到tomcat上很麻烦,把程序共享给同事也很麻烦,需要帮他设置本地的tomcat环境. 在网上找了找其他的Servlet运行环境, ...

  5. 使用vscode对c进行调试

    最近在学习C语言.知道vscode支持对c语言的代码的调试,就想试试.然后找了教程: https://code.visualstudio.com/docs/languages/cpp http://w ...

  6. css 内联与块

    内联元素可以理解为不能直接设置宽度和高度元素,比如span,你为他设置宽度和高度没有效果,除非你把它设置成块级元素. 如下面的代码把display:block;属性值去掉的话,宽度和高度都不会起作用了 ...

  7. sudo:无法解析主机

    原因:替换了hosts文件(之前用了google hosts) 或者更改了主机名称 解决办法:$ pkexec nano /etc/hosts 加入 127.0.1.1  xxxx XXX为主机名字即 ...

  8. 使用git在github上创建新工程

    这段时间进经常会忘记如何在github上同步工程,于是又得查资料,查参考书,浪费了很长时间,因此有了感触,写几篇有关此类问题的篇章! 这是老手新手都十分容易犯的错误,就是在创建一个新github项目或 ...

  9. Servlet 2&period;0 &amp&semi;&amp&semi; Servlet 3&period;0 新特性

    概念:透传. Callback 在异步线程中是如何使用的.?? Servlet 2.0 && Servlet 3.0 新特性 Servlet 2.0 && Servle ...

  10. 彻底解决:java&period;sql&period;SQLException&colon; Incorrect string value&colon; &&num;39&semi;&bsol;xF0&bsol;x9F&bsol;x92&bsol;x94&&num;39&semi; for column &&num;39&semi;name&&num;39&semi; at row 1

    转载:https://blog.csdn.net/qq_31122833/article/details/83992085