Mybatis One-to-many mapping

We can map one-to-many types of results to a collection of objects using the 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 courses;
 //setters & getters
}

The 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.

1. One-to-many mapping with nested ResultMap
We can get the tutor along with the courses' details using a nested ResultMap as follows:


 
 
 
 
 
 


 
 
 
 


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

2. One-to-many mapping with nested select
We can get the tutor along with the courses' details using a nested select query as follows:


 
 
 
 
 



 
 
 
 
 
 

 

In this approach, the 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.

你可能感兴趣的:(Mybatis,one-to-many,mapping)